我正在尝试写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
*/
答案 0 :(得分:3)
使用诺言将多个并行异步请求链接回线性顺序。首先为每个人收集一个诺言,然后做一些事情将它们链接在一起(在这种情况下,我使用了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);