Logik
Logik

Reputation: 219

How to continue loop after 404 response in Angular?

I looked up whether you can just ignore the 404 response and go ahead with your loop but I did not find a solution regarding to Angular, so I want to ask this question here.

I have the following code:

  for(let order of orders){
      this.api.getURL(order.resource_url).then(data =>
          this.detail = data;
      );
      // Do something with this.detail ...
  }

If the request returns a 404 response, the loop should go to the next order and check whether the request returns a correct response or an error again. Can anyone help me out here?

Upvotes: 0

Views: 1167

Answers (2)

shumih
shumih

Reputation: 457

When server responses 404 you receives an exception. To avoid it, you have to catch that error:

for(let order of orders){
  this.api.getURL(order.resource_url).then(data => {
    this.detail = data;
  }, error => {
    // error has been caught
  });
}

UPDATED

You are struggling, because you are trying to use asynchronous api in a synchronous way :) Try to filter failed responses and then do your computations:

Promise.all(
 orders.map(order => this.api.getURL(order.resource_url).catch(() => null))
).then(responses => {
  const successfulResponses = responses.filter(response => response != null)
  for(let data of successfulResponses) {
    // your following code
  }
});

Upvotes: 1

Andreas Rainer
Andreas Rainer

Reputation: 344

As shumih said, you have to catch the error, in the error section you can then call continue; (direct jump to next loop-run), to make sure it executes the next run of your loop. The line: this.detail = data should not be executed anyways when you get a 404 because there's no promise returned, so it doesn't get into this then({}) section.

Upvotes: 1

Related Questions