为什么ESLint在将async函数定义为现有对象的方法时会抛出解析错误以及如何防止它?

时间:2018-01-14 14:39:07

标签: javascript async-await eslint ecmascript-2017

我们假设我们有普通对象

const foo = {}

并且通过使用Promise构造函数语法,我们将以这种方式添加异步方法:

foo.myAsyncMethod = function () {
  return new Promise((resolve, reject) => {
    ...
  })
}

但我们不能这样做(根据ESlint):

foo.myAsyncMethod = async function() {
  ...
}

在已经声明对象之后,将新的异步函数作为方法属性添加到对象的方便方法是什么?

1 个答案:

答案 0 :(得分:2)

看来问题的语法实际上是合法的:

const obj = {}

obj.foo = function () {
  return new Promise((resolve, reject) => {
    resolve(1)
  })
}

obj.bar = async function () {
  return await Promise.resolve(2)
}

obj.foo().then(context => console.log(context))

obj.bar().then(context => console.log(context))

产地:

1
2

由于ESLint给我错误,我得到了它的支持:

enter image description here

此外,要修复ESLint中的解析错误,请将其添加到babelrc文件中:

"parserOptions": {
  "ecmaVersion": 2017
}