(ES6) class (ES2017) async / await getter

試著忘記壹切 提交于 2019-11-30 10:41:53

You can do this

class Foo {
    get bar() {
        return (async () => {
            return await someAsyncOperation();
        })();
    }
}

which again is the same as

class Foo {
    get bar() {
        return new Promise((resolve, reject) => {
            someAsyncOperation().then(result => {
                resolve(result);
            });
        })
    }
}

You can only await promises, and async functions will return promises themselves.
Of course a getter can yield such a promise just as well, there's no difference from a normal value.

You can get the value by await on the caller side.

class Foo {
    get bar() {
        return someAsyncOperation();
    }
}
async function test(){
  let foo = new Foo, val = await foo.bar;
  val.should.equal('baz');
}

Having an async getter implies that you are having a setter expecting an asynchronous value. If the value you expose via your accessors is not asynchronous itself, I am not sure you are using the keywords get / set the right way.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!