Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript forEach manage exceptions

Tags:

I have a forEach loop that check if there are conditions before pushing data in the array:

allow(id, perm, arr) {
  const data = { "userId": id, "permissionId": perm };

  arr.forEach(key => {
    if (id !== key.userId) {
      throw new Error('id does not exists');
    } else {
      if (perm === key.permissionId) {
        throw new Error('perm exists in this id');
      } else {
        arr.push(data);
      }
    }
  });
}

The original array arr is like this:

[{"userId": 1,"permissionId": 1},
 {"userId": 2,"permissionId": 1},
 {"userId": 3,"permissionId": 0},
 {"userId": 4,"permissionId": 0}]

if I use console.log() all works, but when I throw an error the execution stops, but how can I manage the exceptions without stop looping?

like image 962
ufollettu Avatar asked Jul 30 '18 11:07

ufollettu


People also ask

How do you break a loop in forEach?

There is no way to stop or break a forEach() loop other than by throwing an exception.

Can we use continue in forEach JavaScript?

To continue in a JavaScript forEach loop you can't use the continue statement because you will get an error. Instead you will need to use the return statement in place of the continue statement because it will act in the same way when using a forEach because you pass in a callback into the forEach statement.

Can forEach return a value?

Unlike map() , forEach() always returns undefined and is not chainable.


1 Answers

throw is designed to stop your loop/code invocation. If you want to throw those errors after loop, you can push all errors to the array and throw them at the end:

allow(id, perm, arr) {
  const data = { "userId": id, "permissionId": perm };
  const errors = [];

  arr.forEach(key => {
    if (id !== key.userId) {
      errors.push('id does not exists');
    } else {
      if (perm === key.permissionId) {
        errors.push('perm exists in this id');
      } else {
        arr.push(data);
      }
    }
  });

  if (errors.length > 0) {
    throw new Error(errors.join());
  }
}
like image 58
hsz Avatar answered Oct 12 '22 01:10

hsz