2

Let's assume we have plain object

const foo = {}

and by using Promise constructor syntax we would add async method to it this way:

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

but we can't do this (according to ESlint):

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

what is convenient approach to add new async functions to objects as method properties after object is already declared?

Kunok
  • 8,089
  • 8
  • 48
  • 89
  • You can not access the original object being created? – dewwwald Jan 14 '18 at 15:09
  • @dewwwald Nope, it's just ESLint parsing error, please see answer below for more info. – Kunok Jan 14 '18 at 15:10
  • I know that. That is why I am asking. I was bussy writing an answer. So if you have access to the object creation that would make it obvious. See potential solution below. – dewwwald Jan 14 '18 at 15:11

1 Answers1

3

It appears syntax from question is actually legit:

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))

Produces:

1
2

I got cofused by it because of ESLint giving me error:

enter image description here

In addition, to fix parsing errors from ESLint, add this to your babelrc file:

"parserOptions": {
  "ecmaVersion": 2017
}
Kunok
  • 8,089
  • 8
  • 48
  • 89