0

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?

5
  • 1
    Just add a return before apiServiceTwo(resOne) Commented Nov 19, 2020 at 16:55
  • You my sir are my hero, thanks! That did the trick! Commented Nov 19, 2020 at 16:57
  • "I understand why this is happening..." - Then what's the problem in fixing it? o.O Commented Nov 19, 2020 at 17:00
  • 3
    const promiseArr = []; items.forEach(item => { /*...*/ promiseArr.push(p); }) - That's what .map() is for: const promiseArr = items.map(item => { /*...*/ return p; }) Commented Nov 19, 2020 at 17:01
  • @Andreas a lot easier to see now that I've written it out in a simplified format. Commented Nov 19, 2020 at 17:13

1 Answer 1

1

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)
})
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.