I make a async call to get some data. Then, I need to make 3 async calls. After those 3 calls finish I want to do something else. I've tried this:
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);
});
The value pass to doSomething are all undefined. How can I wait for the 3 async calls to complete? I know how to do this as the first step of chain via Promise.all
but not sure how this is accomplished in a then
.
Update
Thanks all for the feedback. Here's what I tried:
Replacing then
with Promise.all
as suggested by @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);
});
The results in an error:
Uncaught TypeError: Cannot read properties of undefined (reading 'all')
As suggested by @DannyMoshe, return Promise
in first then
:
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);
});
call2ReturnValue
& call3ReturnValue
are undefined when calling doSomething
.
My solution
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);
});
From Promise.all documentation, the fulfulliment values are an array of fulfillment values. My previous attempt was not expecting an array.