我正在尝试使用
eachSeries
从
async
图书馆。
根据
this SO Post
,他们说
与async.eachseries的区别在于,每次迭代都将等待异步操作完成,然后再开始下一次迭代。
这就是我想要的。
问题:
我不太懂怎么用
eachSeries
呼叫下一个
异步的
setTimeout
只有在归还内部承诺之后
next()
决定。
我推两个异步
设置超时
我的队列中的函数:
this.dialogTimerQueue.push(this.getNextDialogTimer(data, 1000));
this.dialogTimerQueue.push(this.getNextDialogTimer(data2, 1000));
console.log(this.dialogTimerQueue);
然后尝试遍历:
// https://caolan.github.io/async/docs.html
async.eachSeries(this.dialogTimerQueue, (result) => {
});
问题是
,两者
设置超时
并行运行。他们需要一个接一个地跑。
getNextDialogTimer
返回新的
设置超时
这本身就是一个承诺
下()
getNextDialogTimer: function(dialog, ms) {
let foo = setTimeout(() => {
// only when next() completes, call next in async series
return this.next(dialog);
}, this.npcDialogDelay * ms);
console.log('Timeout: ', foo); // 101 or 102
return foo;
},
下()
承诺:
next: function(dialog) {
var promiseTest = this.screenObj.conversation().addDialogToCenterScreen('npc', dialog, '');
console.log('Next: ', promiseTest);
return promiseTest;
},
console.log显示为:
async.eachSeries(this.dialogTimerQueue, ({dialog, ms}, cb) => {
setTimeout(() => {
console.log('RESOLVING ' + dialog);
this.next(dialog).then(() => {
cb();
});
}, this.npcDialogDelay * ms);
});