原文链接: js 生成器 协程
下一篇: js 前端抠图 性能优化
参考
https://zhuanlan.zhihu.com/p/99977314
看了好几遍还是没看懂....
最简单的生成器, 生产数据
function* range(n) {
for (let i = 0; i < n; i++)
yield i
}
// 0,1,2,3,4,5,6,7,8,9
console.log([...range(10)].join(','))
接受传入的数据
function* start() {
console.log('init')
const mount = yield
mount()
console.log('mount')
const update = yield
update()
console.log('update')
const destory = yield
destory()
console.log('destory')
}
const g = start()
g.next()
setTimeout(
() => g.next(() => console.log('===mount')), 1000
)
setTimeout(
() => g.next(() => console.log('===update')), 2000
)
setTimeout(
() => g.next(() => console.log('===destory')), 3000
)
// 每隔一秒, 顺序输出
// init
// ===mount
// mount
// ===update
// update
// ===destory
// destory
递归扁平化数组
此做法相比于传统的递归实现,在于其可以处理无限深度的元素(传统递归在这里就挂掉了)
function* flatten(list) {
for (let i of list) {
if (Array.isArray(i))
yield* flatten(i)
else
yield i
}
}
console.log(
[...flatten([
1,
[1, 2],
[[
3, 4, [5, 6]
]]
])]
)
// [
// 1, 1, 2, 3,
// 4, 5, 6
// ]
简单的调度
const sleep = ms =>
new Promise(resolve => {
setTimeout(resolve, ms);
});
async function task1() {
while (true) {
await sleep(Math.random() * 1000);
console.log("task1");
}
}
async function task2() {
while (true) {
await sleep(Math.random() * 1000);
console.log("task2");
}
}
async function task3() {
while (true) {
await sleep(Math.random() * 1000);
console.log("task3");
}
}
function main() {
task1();
task2();
task3();
console.log("start task");
}
main();