我想
那是怎么做的?
类似的东西-但请在第5行的注释中查看问题
var urls = []; // a bunch of URLs
Promise.all(
urls.map(e => {
return $.post(e);
// do something here after post has succeded
/// but still return a promise
})
).then(d => {
// do something when all succeed
}).catch(e => {
console.log(e)
})
我可以使用Bluebird
答案 0 :(得分:1)
我认为您的问题很清楚,没有一堆代码。要了解的重要一点是.then()
返回了诺言。这意味着您可以通过调用then()
来解决单个promise并保存来自then()
的返回值(这也是数组中的promise)时的工作。您将把该数组传递给Promise.all()
,当该数组中的所有promise都解决时,它将解析:
/* some async function */
let asyncFn = () => new Promise(resolve => setTimeout(() => resolve(Math.random()), Math.floor(Math.random() * 1500)))
let promises = []
for (let i = 0; i < 10; i++) {
let p = asyncFn() // then() returns a promise, save it in the array:
.then((r) => { // do work for each promise
console.log('done:', i, "returned: ", r)
return r // Promise.all() will received these values as an array
})
promises.push(p) // promises is array of promises
}
// Promise.all() runs when all promises in array have resolved
Promise.all(promises)
.then((arr) => console.log("Everything finished. Final values: ", arr))