我试图使用生成器来阻止setTimeOut上的执行流。我做错了什么?我不能每隔1500毫秒就把console.log拿出来。我是节点新手,如果我做了一件很愚蠢的事,请不要用心灵感应杀死我
['1', '2', '3'].forEach(function* iteration(index) {
// Some logic here
yield setTimeout(() => console.log('sick of this!'), 1500)
iteration.next(index)
})
发布于 2016-07-08 11:24:47
可悲的是你不能。Array.prototype.forEach是一个更高级别的函数,它只调用给定的回调,但是不会也不能使用生成器。我的意思是,你可以给一个发电机,因为发电机只是正常的函数,但它们不能运行,你不能产生值。
第二件事是,你只会给出超时时间-s,我很确定你想等1500 ms。
因此,您必须摆脱forEach,转而使用for..of,并且必须编写一个延迟函数,使用异步/等待,如下所示:
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));如果您希望使用常规的节点回调,这是有点困难,不太好,但绝对有可能。如果允许您选择,我建议您使用异步/等待方式。
发布于 2016-07-12 17:28:41
也许你可以这样做;
['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
});
或者按照ES6承诺的作业队列异步化的建议
['1', '2', '3'].forEach(e => {function *iteration(index) {
// Some logic here
var val = yield Promise.resolve(index).then(v => it.next(v)); // async by the job queue
setTimeout(_ => console.log('sick of this..! '+ val), 1500*val);
}
var it = iteration(e);
it.next(); // start the engine
});
https://stackoverflow.com/questions/38265269
复制相似问题