gpt4 book ai didi

javascript - 使动态创建的 promise 按顺序执行

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

如何动态创建一系列 promise 并让它们按顺序执行?

pseudocode
for x=0 to maxValue
promiseArray.push(createNewPromise(x))

executeAllPromisesSequentially(promiseArray)

在哪里

executeAllPromisesSequentially is functionally equivalent to

promise1()
.then(promise2)
.then(promise3)
etc
...

最佳答案

我的 gist 上显示了一些图案

使用 Reduce 的 Promise 迭代

let tasks = [ /* ... */ ]
let promise = tasks.reduce((prev, task) => {
return prev.then(() => {
return task();
});
}, Promise.resolve());
promise.then(() => {
//All tasks completed
});

顺序迭代模式

let tasks = [ /* ... */ ]
let promise = Promise.resolve();
tasks.forEach(task => {
promise = promise.then(() => {
return task();
});
});
promise.then(() => {
//All tasks completed
});

顺序迭代示例

function spiderLinks(currentUrl, body, nesting) {
let promise = Promise.resolve();
if(nesting === 0) {
return promise;
}
const links = utilities.getPageLinks(currentUrl, body);
links.forEach(link => {
promise = promise.then(() => spider(link, nesting - 1));
});
return promise;
}

关于javascript - 使动态创建的 promise 按顺序执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49685980/

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