-2

I have the following code

try {

    for (const customer of customers)
    {
         followUser(ig, customer.trim());
    }



} catch (err){
      console.log('ERROR: ' + " " + err);
}

followUser is an API call.. which sometimes out of the blue can return 400 or 404 errors when server has issues.. how do I break out of the for loop when one of the followUser generates an error?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
aherlambang
  • 14,290
  • 50
  • 150
  • 253

3 Answers3

0

The problem with procedural loops and async calls is that you'll often try to access the data you're supposed to get before it's even fetched.

You might want to look at Promises, which are objects storing your request and that automatically change when the request ends. You can use multiple functions including Promise.all() which calls a function for each element you supply. You can then catch the error if one of them fails and handle the error the way you want.

More info here : Promise, Promise.all()

Raekh Void
  • 441
  • 3
  • 11
0

Since followUser is an API call (so an asynchronous operation), I believe you should be using promises to make sure the flow goes alright. The Promise library should have something you can use.

This question on StackOverflow might be helpful for you. :)

saglamcem
  • 677
  • 1
  • 8
  • 15
0

Try this code:

for (const customer of customers) {
    try {
        followUser(ig, customer.trim());
    } catch (err) {
        console.log('ERROR: ' + err);
        break;
    }
}
stefanhorne
  • 1,619
  • 3
  • 16
  • 23
Abdelhamid
  • 11
  • 1
  • 1
    a try block inside a try block ? – aherlambang Feb 13 '20 at 16:11
  • A try block within a try block isn't necessarily a bad thing. I think that in this case it does actually make sense, assuming there is more code in the outer try block whose exceptions need to be caught. If the code provided is the only code there is then it would make sense to simply move the try block into the loop. https://softwareengineering.stackexchange.com/questions/118788/is-using-nested-try-catch-blocks-an-anti-pattern – stefanhorne Feb 13 '20 at 16:30
  • No, just move the try block inside the loop block, replace ur code by mine. – Abdelhamid Feb 14 '20 at 10:18