Reputation: 10608
I'm trying to accomplish a task with an array of nested API calls.
I currently have something like this set up:
const items = [1, 2]
const promiseArr = []
items.forEach(item => {
const p = apiServiceOne().then(resOne => {
console.log("We've got what we need for the 2nd call for item", item)
apiServiceTwo(resOne).then(resTwo => {
console.log("We've got the data we need for item", item)
})
})
promiseArr.push(p)
})
Promise.all(promiseArr).then(() => console.log("Done"))
Currently the result I get is the following:
"We've got what we need for the 2nd call for item 1"
"We've got what we need for the 2nd call for item 2"
"Done"
"We've got the data we need for item 2"
"We've got the data we need for item 1"
I understand why this is happening but I'm not sure how to update my code to wait for the nested API call to be completed before printing "Done"
.
How can I wait from the inner API call to be done before running the "Done"
log at the end?
Upvotes: 0
Views: 375
Reputation: 2171
Return your second Promise to fix the broken chain:
items.forEach(item => {
const p = apiServiceOne().then(resOne => {
console.log("We've got what we need for the 2nd call for item", item)
return apiServiceTwo(resOne).then(resTwo => {
console.log("We've got the data we need for item", item)
})
})
promiseArr.push(p)
})
Upvotes: 1