You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 09:15:58