简体   繁体   English

Cleancode:在Promise中尝试/捕获

[英]Cleancode: try/catch in Promise

I am working on redux-form atm and found the piece of code. 我正在使用redux-form atm并找到了这段代码。 Its working for me but is there any cleaner way to write this in ES6 style? 它为我工作但是有没有更清洁的方式来写这个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);
    }
  });
};

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. try / catch在promise链和promise执行器函数中是多余的。

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. 调用你的函数的promise代码负责这个。 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: 您可以使用Conditional(三元)运算符来简化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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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