控制每个循环nodejs中的执行stream程

我试图停止setTimeOut使用生成器的执行stream程。 我究竟做错了什么? 我不能每1500毫秒获取console.log。 我是新的节点,请不要心灵感应杀死我,如果我做一个非常愚蠢的事情

['1', '2', '3'].forEach(function* iteration(index) { // Some logic here yield setTimeout(() => console.log('sick of this!'), 1500) iteration.next(index) }) 

可悲的是你不能。 Array.prototype.forEach是一个更高级别的函数,它只是调用给定的callback函数,但是不会也不能采用生成器。 我的意思是你可以给发电机作为发电机只是正常的function,但他们不会运行,你不能产生价值。

第二件事是,你只会产生timeoutId-s,我很确定你想等待1500毫秒。

所以你将不得不摆脱forEach,而是使用for..of,而不得不写一个延迟函数,使用asynchronous/等待它看起来像:

 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)); 

你可以用babel来传递它。

如果你想使用常规的节点callback,那有点困难,不太好,但绝对有可能。 如果你可以select,我build议你使用asynchronous/等待的方式。

也许你可以这样做;

 ['1', '2', '3'].forEach(e => { function *iteration(index) { // Some logic here var val = yield setTimeout(_ => it.next(index),0); // make async setTimeout(_ => console.log('sick of this..! '+ val), 1500*val); } var it = iteration(e); it.next(); // start the engine });