简体   繁体   中英

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?!

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.

You can use Conditional (ternary) Operator to simplify if-statement , also you don't need a catch block here:

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

//ES6 - using "generators"
const asyncValidate = function* (values) {
    return yield ['john', 'paul', 'george', 'ringo'].includes(values.name) ? Promise.reject('That username is taken') : Promise.resolve();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM