Search code examples
javascriptecmascript-6es6-promise

Can I use ternary operators to handle errors in a promise?


Is something like this:

function gets3Objects(eventsArray) {
  return new Promise((resolve, reject) => {
    s3.listObjects(params, (err, data) => {
      err
        ? reject(err)
        : resolve(eventsArray.forEach((file) => {
          params.Key = file;
        }));
    });
  });
}

Considered good practice? If not, what would be a better alternative to error handling in a javascript promise?


Solution

  • You can, but you shouldn't. Ternary operators are for when you need an expression - when you need to store or assign the result to something. Otherwise, like here, you should use ordinary if/else statements.

    (This being a Promise has nothing to do with the appropriateness of a ternary operator)