我正在尝试使用生成器停止 setTimeOut 上的执行流程。我究竟做错了什么?我无法让 console.log 每 1500 毫秒退出一次。我是 node 的新手,如果我在做一件非常愚蠢的事情,请不要用心灵感应杀死我
['1', '2', '3'].forEach(function* iteration(index) {
// Some logic here
yield setTimeout(() => console.log('sick of this!'), 1500)
iteration.next(index)
})
最佳答案
可悲的是你做不到。 Array.prototype.forEach
是一个更高级别的函数,它只是调用给定的回调,但不会也不能使用生成器。我的意思是你可以给一个生成器,因为生成器只是普通函数,但它们不会运行,你不能产生值。
第二件事是你将只产生 timeoutId-s,我很确定你想要等待 1500 毫秒。
所以你将不得不摆脱 forEach 并使用 for..of 来代替,并且将不得不编写一个延迟函数,使用 async/await 它看起来像:
function delay(time, value) {
return new Promise(resolve => { setTimeout(() => { resolve(value); }, time); });
}
async function main() {
for (var item of ['1', '2', '3']) {
await delay(1000);
console.log(item);
}
}
main().then(null, e => console.error(e));
You can transpile it with babel.
如果你想使用常规的 Node 回调,那会有点困难而且不太好,但绝对有可能。如果让你选择,我建议你使用async/await方式。
关于javascript - 控制.each循环nodejs内的执行流程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38265269/