【问题标题】:Unexpected destructuring with Promise.all in ES5在 ES5 中使用 Promise.all 进行意外解构
【发布时间】:2019-09-30 02:39:18
【问题描述】:

我正在使用Promise.all 调用一组 Promise。我们的开发版本只支持 ES5。因此,当我使用以下语句时,ESLINT 会引发错误:

Promise.all([
  service.document.getDocumentByPath( grantorPath ),
  service.document.getDocumentByPath( synonymPath ),
  service.document.getDocumentByPath( templatePath )
]).then(function([grantorDoc, synonymDoc, templateDoc]) {

ESLint error : Unexpected destructuring. eslint(es5/no-destructing)

我愿意

  1. 在不触及 eslint 规则的情况下移除 ESLINT 错误。
  2. 使用 Promise 解决后收到的结果(grantorDoc、synonymDoc、templateDoc)。

【问题讨论】:

  • 禁用下一行的控件怎么样? stackoverflow.com/questions/27732209/…
  • 那么您是否尝试编写代码以使用解构?您可以通过不编写 ES5 中无效的代码来消除错误。
  • 正如我在问题中提到的,我不想触及 ESLINT 规则。
  • 为什么不能使用不使用解构的代码?
  • 对象解构是 es6 自带的,所以如果你不想更改 eslint 规则,请遵循它们。

标签: javascript ecmascript-6 es6-promise eslint ecmascript-5


【解决方案1】:

你的 ESLint 插件forbids destructuring。由于听起来您的代码需要与 ES5 兼容,因此请在函数的第一行声明这些变量:

Promise.all([
  service.document.getDocumentByPath( grantorPath ),
  service.document.getDocumentByPath( synonymPath ),
  service.document.getDocumentByPath( templatePath )
]).then(function(result) {
  var grantorDoc = result[0];
  var synonymDoc = result[1];
  var templateDoc = result[2];
  // ...
});

(也就是说,如果您希望能够阅读和编写简洁易读的代码,那么使用 ES6+ 编写并稍后使用 Babel 自动将代码转换为 ES5 可能更有意义)

确保您的环境支持 Promise.all,因为它是 ES6 功能 - 如果您还没有,请使用 polyfill。

【讨论】:

  • 顺便说一句,Promises 在 ES6 中进入了 JS。这可能实际上是在使用 Bluebird 或其他替代方案,但 OP 可能希望对此进行更多研究。如果这个 一个 ES6 承诺,那么它可能不应该是。或者它可能表示 ES6 代码没问题。
猜你喜欢
  • 2020-06-07
  • 2021-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-10
  • 2011-07-04
  • 2021-06-06
相关资源
最近更新 更多