async function fnGetVehicleList(makeCode, responseModels){
let vehicleListData = [];
await Promise.all(responseModels.Table.forEach(async (model) => {
const vehicleDetailResponse = await getVehicleDetails('2024',makeCode, model.Code); // API call. This is also an Async function
await Promise.all(vehicleDetailResponse.Table.forEach(async (vehicleItem)=>{
vehicleListData.push(vehicleItem);
}));
}));
return vehicleListData;
}
Here the vehicleListData is not waiting until both the forEach loops are executed.
It waits till, it makes the API call for all the items in responseModels forEach Loop. But once the API call is made, it is not awaiting the second forEach loop i.e. (vehicleDetailResponse.Table.forEach) and simply returns the vehicleListData which is empty data from the function.
Please let me know how to wait the second forEach loop is also executed and then function to return the response
forEach
does not return a Promise, nor does push
. You should rewrite the code to use Promise.all
which resolves an array of values, and flat(1)
to unpack the nested responses. This shows how to use Promises as values rather than simply using them as timing to control side effects -
async function fnGetVehicleList(makeCode, responseModels) {
const all = await Promise.all(responseModels.Table.map(model =>
getVehicleDetails('2024', makeCode, model.Code)
))
return all.flat(1)
}