Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleancode: try/catch in Promise

I am working on redux-form atm and found the piece of code. Its working for me but is there any cleaner way to write this in ES6 style?

const asyncValidate = (values/* , dispatch */) => {
  return new Promise((resolve, reject) => {
    try {
      if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
        const error = {
          name: 'That username is taken'
        };
        throw error;
      }
      resolve();
    } catch (e) {
      reject(e);
    }
  });
};

I would appreciate your help


Solution

const asyncValidate = (values/* , dispatch */) => {
  return new Promise((resolve, reject) => {
    const errors = {};
    if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
      errors.name = 'That username is taken';
    }
    reject(errors);
  });
};

probably cleaner way?!

like image 689
tomole Avatar asked Jan 08 '17 14:01

tomole


People also ask

Can I use try catch inside promise?

If you throw an error inside the promise, the catch() method will catch it, not the try/catch. In this example, if any error in the promise1, promise2, or promise4, the catch() method will handle it.

How do you catch an error in a promise?

catch " around the executor automatically catches the error and turns it into rejected promise. This happens not only in the executor function, but in its handlers as well. If we throw inside a . then handler, that means a rejected promise, so the control jumps to the nearest error handler.

Does catch return a promise?

catch() The catch() method returns a Promise and deals with rejected cases only. It behaves the same as calling Promise.


1 Answers

try/catch is redundant in promise chains and promise executor functions.

Any error thrown is automatically converted to a rejection of the promise you're supposed to return. The promise code calling your function takes care of this. So just do:

const asyncValidate = values => new Promise(resolve => {
  if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
    throw { name: 'That username is taken'};
  }
  resolve();
});

and it gets converted to a rejection.

like image 117
jib Avatar answered Sep 29 '22 12:09

jib