Cleancode:在Promise中尝试/捕获

时间:2017-01-08 14:52:02

标签: javascript ecmascript-6 coding-style es6-promise

我正在使用redux-form atm并找到了这段代码。它为我工作,但有没有更清洁的方式来写ES6风格?

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);
    }
  });
};

感谢您的帮助

解决方案

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);
  });
};
可能更干净的方式?!

2 个答案:

答案 0 :(得分:18)

try / catch在承诺链和承诺执行函数中是多余的。

抛出的任何错误都会自动转换为拒绝您应该返回的承诺。调用你的函数的promise代码负责这个。所以就这样做:

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

并将其转换为拒绝。

答案 1 :(得分:0)

您可以使用Conditional (ternary) Operator来简化if-statement,此处也不需要使用catch块:

//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();
}