SetTimeout:按顺序排队事件
SetTimeout: Queue Events in Order
我正在尝试编写 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
*/
使用承诺将多个并行异步请求链接回线性顺序。首先为每个收集一个承诺,然后做一些事情将它们链接在一起(在这种情况下我使用了 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);
我正在尝试编写 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
*/
使用承诺将多个并行异步请求链接回线性顺序。首先为每个收集一个承诺,然后做一些事情将它们链接在一起(在这种情况下我使用了 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);