(ES6) class (ES2017) async / await getter

前端 未结 4 1953
我寻月下人不归
我寻月下人不归 2020-12-08 08:58

Is it or will it be possible to have an ES6 class getter return a value from an ES2017 await / async function.

class Foo {
    async get bar() {
        var          


        
4条回答
  •  眼角桃花
    2020-12-08 09:50

    For the value returned by the getter, this changes nothing, since an async function returns a Promise anyway. Where this matters, is in the function, since await can only be used in an async function.

    If the issue it that await is wished in the function, I would do:

    get property () {
      const self = this; // No closure with `this`, create a closure with `self`.
      async function f () { // `async` wrapper with a reference to `self`
        const x = await self.someFunction(); // Can use `await`
        // the rest with “self” in place of “this”
        return result;
      }
      return f(); // Returns a `Promise` as should do an `async get`
    }
    

提交回复
热议问题