如何在Promise链的then中等待多个异步调用完成后执行下一个then?
问题:Promise链中等待多个异步调用完成的正确方式
我需要先发起一个异步调用获取数据,接着执行3个异步调用,等这3个调用全部完成后再进行后续操作。我写了如下代码:
let outerApi; getApi(url).then(function(api) { outerApi= api; return doSomething(api, "cars"); }).then((cars) => { //3 async calls call1(outerApi, cars); call2(outerApi, cars); call3(outerApi, cars); }).then(call1ReturnValue, call2ReturnValue, call3ReturnValue => { doSomething(call1ReturnValue, call2ReturnValue, call3ReturnValue); });
但传入doSomething的参数全为undefined。我知道在Promise链的开头可以用Promise.all实现等待多个异步完成,但不清楚怎么在then里实现。
更新
感谢大家的反馈,我尝试了以下方案:
方案一:用Promise.all替换then
按照@ControlAltDel的建议修改后代码如下:
let outerApi; getApi(url).then(function(api) { outerApi= api; return doSomething(api, "cars"); }).Promise.all([ //3 async calls call1(outerApi, cars), call2(outerApi, cars), call3(outerApi, cars)]) ).then(call1ReturnValue, call2ReturnValue, call3ReturnValue => { doSomething(call1ReturnValue, call2ReturnValue, call3ReturnValue); });
结果报错:Uncaught TypeError: Cannot read properties of undefined (reading 'all')
方案二:在then中返回Promise
按照@DannyMoshe的建议修改后代码如下:
let outerApi; getApi(url).then(function(api) { outerApi= api; return doSomething(api, "cars"); }).then((car) => { return Promise.all([ //3 async calls call1(outerApi, cars), call2(outerApi, cars), call3(outerApi, cars)]); ).then(call1ReturnValue, call2ReturnValue, call3ReturnValue => { doSomething(call1ReturnValue, call2ReturnValue, call3ReturnValue); });
调用doSomething时call2ReturnValue和call3ReturnValue为undefined。
我的解决方案
let outerApi; getApi(url).then(function(api) { outerApi= api; return doSomething(api, "cars"); }).then((car) => { return Promise.all([ //3 async calls call1(outerApi, cars), call2(outerApi, cars), call3(outerApi, cars)]); ).then(([call1ReturnValue, call2ReturnValue, call3ReturnValue]) => { doSomething(call1ReturnValue, call2ReturnValue, call3ReturnValue); });
Promise.all的兑现值是一个包含所有异步调用兑现值的数组,之前的尝试没有对这个数组进行解构,导致参数无法正确获取。
内容的提问来源于stack exchange,提问作者James
相关产品推荐
相关产品推荐

