【发布时间】:2021-01-13 05:17:34
【问题描述】:
我正在尝试通过以下方式运行两个承诺:
Promise.all([...])
但他们都有自己的.then:
Promise.all([promise1().then(...), promise2().then(...)])
我希望在 Promise.all 上运行另一个 .then,同时等待 .then 返回,如果这有意义的话。
这是一个fiddle,说明了我的意思。
【问题讨论】:
我正在尝试通过以下方式运行两个承诺:
Promise.all([...])
但他们都有自己的.then:
Promise.all([promise1().then(...), promise2().then(...)])
我希望在 Promise.all 上运行另一个 .then,同时等待 .then 返回,如果这有意义的话。
这是一个fiddle,说明了我的意思。
【问题讨论】:
如果你跑了
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
return Promise.all(ps.map(rejection))
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
Promise.all([p1, p2]).then(()=>{
console.log("3")
})
})()
那么结果就是正确的
1
2
3
If you run
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
return Promise.all(ps)
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
doAll(p1, p2).then(()=>{
console.log("3")
})
})()
那你又答对了
1
2
3
因此,问题出在ps.map(rejection) 部分。让我们看看:
function get1() {
return new Promise((r)=>setTimeout(() => r(),3000))
}
function rejection() {/*Handle rejection*/}
function doAll(...ps) {
console.log(ps);
console.log(ps.map(rejection));
return Promise.all(ps.map(rejection));
}
(async () => {
var p1 = get1().then(()=>console.log("1"));
var p2 = get1().then(()=>console.log("2"));
doAll(p1, p2).then(()=>{
console.log("3")
})
})()
输出
两个元素的数组,都是undefined,计算起来很简单。因为ps.map(rejection)是一个箭头函数,将其参数命名为reject,不返回任何东西。
【讨论】:
如果您想在 javascript 中使用异步操作,可以使用 3 种方式。
为了实现你想要的确切的东西,最好和优化的方法是使用 async/await 方法。
你可以这样做:
async function getAllData(){
const p1 = await promise1;
const p2 = await promise2;
}
现在 getAllData 返回 Promise,你可以使用 .then() 获取结果,使用 .catch() 获取错误。
要阅读有关语法和其他功能的更多信息,您可以访问此站点:explain about async and await
【讨论】:
the best and the optimized way is using the async/await method 不,不是。 OP 希望并行执行承诺。 await 是串行的。