gpt4 book ai didi

javascript - 按返回 promise 顺序调用多个 setTimeouts

转载 作者:行者123 更新时间:2023-11-29 23:21:06 25 4
gpt4 key购买 nike

我正在尝试使用 eachSeries 同步运行一组异步函数来自 async 库。

根据 this SO Post , 他们说

The difference with async.eachSeries is that each iteration will wait for the async operation to complete before starting the next one.

这就是我想要的。

问题:我不太明白如何使用eachSeries 来调用下一个async setTimeout only在返回的内部 promise next() 解决后。

我将两个异步 setTimeout 函数推送到我的队列中:

this.dialogTimerQueue.push(this.getNextDialogTimer(data, 1000));
this.dialogTimerQueue.push(this.getNextDialogTimer(data2, 1000));
console.log(this.dialogTimerQueue); //  [101, 102]

然后尝试遍历:

// https://caolan.github.io/async/docs.html#eachSeries
async.eachSeries(this.dialogTimerQueue, (result) => {

});

问题是,两个setTimeout是并行运行的。他们需要一个接一个地运行。

getNextDialogTimer 返回一个新的 setTimeout,它本身返回一个 Promise next()

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() promise :

// Return promise
next: function(dialog) {
var promiseTest = this.screenObj.conversation().addDialogToCenterScreen('npc', dialog, '');
console.log('Next: ', promiseTest);
return promiseTest;
},

Console.log 显示为:

enter image description here


    async.eachSeries(this.dialogTimerQueue, ({dialog, ms}, cb) => {
setTimeout(() => {
console.log('RESOLVING ' + dialog);
this.next(dialog).then(() => {
cb();
});
}, this.npcDialogDelay * ms);
});

最佳答案

问题是,当您调用 getNextDialogTimer 时,您会立即启动/设置 timeout - 这是该函数的第一行。它们一添加到队列就开始,这不是您想要的。

您可以将一个可调用 函数加入队列,它会在调用时启动超时。或者,您可以将 dialog, ms 项目排队,这可能更容易理解,例如:

const dialogTimerQueue = [];
const data = 'foo';
const data2 = 'bar';
const npcDialogDelay = 1;
const next = () => new Promise(resolve =>
setTimeout(() => {
console.log('next resolved');
resolve();
}, 500)
);

dialogTimerQueue.push({ dialog: data, ms: 1000 });
dialogTimerQueue.push({ dialog: data2, ms: 1000 });
async.eachSeries(dialogTimerQueue, ({ dialog, ms }, cb) => {
setTimeout(() => {
console.log('resolving ' + dialog);
next().then(cb);
}, npcDialogDelay * ms);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/async/2.6.1/async.min.js"></script>

关于javascript - 按返回 promise 顺序调用多个 setTimeouts,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50615333/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com