【问题标题】:ESLint consistent-return error with Promise带有 Promise 的 ESLint 一致返回错误
【发布时间】:2016-09-10 08:57:10
【问题描述】:

我在以下代码的第一行得到consistent-return ESLint error

return new Promise((resolve, reject) => { 
  if (condition) {
    asyncMethod.then(data => {
      return resolve(syncMethod());
    }, err => reject(err));
  } else {
    return resolve(syncMethod());
  }
});

返回不一致的缺失情况是什么,应该如何修复?

【问题讨论】:

    标签: javascript ecmascript-6 es6-promise eslint


    【解决方案1】:

    ESlint 没有捕捉到这一点,但你应该完全avoid the Promise constructor

    return (condition ? asyncMethod : Promise.resolve()).then(data => syncMethod());
    

    返回不一致的缺失情况是什么?

    你没有在 Promise 构造函数的 if 块中 returning 任何东西。或者更确切地说,您不应该在 else 块中使用 returned 调用 resolve() 的结果。

    【讨论】:

      【解决方案2】:

      您不会从该 if 块中返回值:

      if (condition) {
        asyncMethod.then(data => {
          return resolve(syncMethod());
        }, err => reject(err));
      }
      

      这意味着如果condition为真,该函数将返回undefined,如果为假,则返回resolve函数的结果。

      【讨论】:

      • 哦,有道理,你能建议如何解决它吗?
      • 当然,只需添加一个返回值,这取决于您使用它的目的,但它可能只适用于return asyncMethod.then(data => { return resolve(syncMethod()); }, err => reject(err));
      猜你喜欢
      • 2016-08-06
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-19
      • 2017-10-13
      • 2016-01-22
      相关资源
      最近更新 更多