gpt4 book ai didi

javascript - 使用 Promise.all() 实现 promise 时执行操作

转载 作者:可可西里 更新时间:2023-11-01 01:17:07 25 4
gpt4 key购买 nike

我可以使用 Promise.all(array) 异步解决一堆 promise 。然而 .then() 只有在所有这些 promise 都已解决后才会运行。当 promise 得到解决时,我如何执行操作?

例如,我想使用 Promise.all() 异步加载一篇文章中的所有段落 - 这样网络请求就会立即触发。如果第 1 段完成加载,我希望它呈现到页面 - 但只有当它在第 2 段之前完成加载时,我才希望第 2 段加载。如果第 3 段已完成加载而第 2 段未完成,我希望第 3 段在呈现到页面之前等待第 2 段。等等。

我试过这样的事情,但我不知道下一步该怎么做:

var getStuff = function(number, time){
return new Promise(function(resolve, reject){
window.setTimeout(function(){resolve(`${number} - Done.`)}, time);
});
};

Promise.all([ getStuff(1, 200),
getStuff(2, 100),
getStuff(3, 250),
getStuff(4, 200),
getStuff(5, 300),
getStuff(6, 250),
getStuff(7, 5000)])
.then(function(data){
console.log(data);
});

我怎样才能让数据的控制台日志一个接一个地发生——在发出下一个请求之前不用 then() 解决每个 promise ?有更好的方法吗?

最佳答案

您无法使用 Promise.all 实现此顺序,因为从 Promise.all 返回的 promise 会等待所提供数组中的所有 promise 同时解析(与顺序相反) ) 在它自己解决之前。

相反,您可以单独创建 promise 并同时触发他们的请求:

// create promises and make concurrent requests
const s1 = getStuff(1, 200);
const s2 = getStuff(2, 100);
const s3 = getStuff(3, 250);
// ...

然后创建一个关于如何处理它们的 react 链(stuff1 在 stuff2 之前,stuff2 在 stuff3 之前,等等)

// create a chain of reaction order to the results of parallel promises
s1
.then(console.log) // s1 resolved: log result
.then(() => s2) // chain s2
.then(console.log) // s2 resolved: log result
.then(() => s3) // chain s3
// ...
.then(() => { // chain another function at at the end for when all promises resolved
// all promises resolved (all data was logged)
}

要按照创建 promise 的相同顺序对 promise 结果使用react,您可以更改 getStuff 函数以使用 Array.prototype.reduce 动态链接 react :

var times = [200, 100, 250, 200, 300, 250, 5000];

var getStuff = function(time, index) { // swap the order of arguments so number is the index passed in from Array.map
return new Promise((resolve, reject) => {
window.setTimeout(() => {
resolve(`${index + 1} - Done.`); // use index + 1 because indexes start at 0
}, time);
});
};

times
// map each time to a promise (and number to the index of that time + 1) and fire of a request
.map(getStuff)
// dynamically build a reaction chain for the results of promises
.reduce((chain, promise) => {
return chain
.then(() => promise)
.then(console.log);
}, Promise.resolve())
.then(() => {
// all promises resolved (all data was logged in order)
});

关于javascript - 使用 Promise.all() 实现 promise 时执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728793/

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