Manasi Sharma Manasi Sharma - 5 months ago 38
Node.js Question

Break out of async completely if condition met

How to make a async.each loop break and return a specific value / error when a condition is met. For instance, in this case, if status exists i wish to return something from the function 'check' rather than iterating through rest of the items. Any suggestions?

const check = (condition) => {

if (condition === 100) {

async.each(items, (item, callback) => {

if (status) {

callback(Boom.conflict('Conflict'));
} else {

// some logic
callback(destroyInstance);
}
});
}
};

Answer

As async.each works parallely on each item in items array. It does not looks to be possible to stop the action at any condition, because the order of execution of items are not deterministic here. I guess you should use async.eachSeries instead.

So whenever the condition is met what you should do is throw an error (return callback(err)), what this will do is it will stop executing further. And if you want to send some value instead of throwing and error, You can just pretend to send an error and while checking in the main callback of async.eachSeries you just check the type of value u have got from the iteratee callback function as u can see for example:

async.eachSeries(items, function iteratee(item, callback) {
  if (status) {
    return callback(E/V); // error(E) or value(V) u want to send to the done function
  } else {
    // some logic
    callback();
  }
 }, function done(e) {
  if(e){
    if(type of e === TYPE OF RETURN VALUE U WANTED) // or any other logic u can come up with
     return cb(null, e);
    else return cb(e);
  }
  else cb(null, //...);
});

Tell me if it works.