Cleancode:在承诺中尝试/捕捉
我正在开发Redux-Form自动取款机,找到了这段代码。这对我来说很有效,但有没有更干净的方式来用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);
});
};
可能是更干净的方式?!
解决方案
try
/catch
在承诺链和承诺执行人功能中是多余的。
const asyncValidate = values => new Promise(resolve => {
if (['john', 'paul', 'george', 'ringo'].includes(values.name)) {
throw { name: 'That username is taken'};
}
resolve();
});
并转换为拒绝。
相关文章