user2837961
user2837961

Reputation: 1555

For loop to call API function and wait for it

I have my data going into a API in a loop as below. How can I ensure that the next iteration is called when the first is finished? Image my API takes a second for each element

saveMyData(){
  this.elements.forEach(element => {
    CALL_MY_API.read(element)
    .then(response =>  {
        // comes here in 1 second
        // do something with response
    }
    .catch(error => {
       this.showError(error)
    })
 })
}

Upvotes: 0

Views: 2348

Answers (1)

Thomas
Thomas

Reputation: 181755

This starts a bunch of asynchronous operations in parallel. I assume that's not what you want, and you want to wait for one to actually finish before starting the next one.

It's easiest if you can use async/await syntax:

async saveMyData() {
  for (const element of this.elements) {
    try {
      const response = await CALL_MY_API.read(element)
      // do something with response
    } catch (error) {
      this.showError(error)
    }
  }
}

If you can't, you'll need to chain the promises manually:

saveMyData() {
  // Start with an immediately resolved promise.
  let promise = new Promise((resolve, reject) => resolve())
  // Add each element to the chain.
  this.elements.forEach(element => {
    promise = promise.then(() => {
      return CALL_MY_API.read(element)
        .then(response => {
          // do something with response
        })
        .catch(error => {
          this.showError(error)
        })
    })
  })
}

Upvotes: 3

Related Questions