gpt4 book ai didi

javascript - SetTimeout:按顺序排列事件

转载 作者:行者123 更新时间:2023-11-28 17:00:46 25 4
gpt4 key购买 nike

我正在尝试编写triggerActions,以便可以按顺序打印processActions结果。我下面的内容将首先等待 Process Action 1 打印,然后打印并等待 Process Action 2...5

function triggerActions(count) {
let counter = 1
processAction(counter, fn)

function fn(string) {
console.log(string)

if (counter >= count) {
return
}
counter++
processAction(counter, fn)
}

}

function processAction(i, callback) {
setTimeout(function() {
callback("Processed Action " + i);
}, Math.random() * 1000);
}

triggerActions(5);

/**
* Result---
* Processed Action 1
* Processed Action 2
* Processed Action 3
* Processed Action 4
* Processed Action 5
*/

但是,我希望 triggerActions 执行以下操作:

/** Process action 3 // log nothing
* Process action 2 // log nothing
* Process action 1 // log processed Action 1, process action 2, ...
* Process action 4 // log process action 4
* process action 5 // log process action 5
*/

最佳答案

使用 Promise 将多个并行异步请求链接回线性顺序。首先收集每个 promise ,然后做一些事情将它们链接在一起(在本例中我使用了reduce)。

async function triggerActions(count) {
const promises = [];
for (let i = 1; i <= count; i++) {
promises.push(new Promise((resolve) =>
processAction(i, resolve)
));
}
promises.reduce((a, b) => a.then(console.log).then(() => b)).then(console.log);
}

function processAction(i, callback) {
setTimeout(() => {
console.log(`Completed ${i}`)
callback(`Processed Action ${i}`);
}, Math.random() * 1000);
}

triggerActions(5);

关于javascript - SetTimeout:按顺序排列事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57583218/

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