(ES6) class (ES2017) async / await getter

前端 未结 4 1964
我寻月下人不归
我寻月下人不归 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:48

    Update: As others have pointed out, this doesn't really work. @kuboon has a nice workaround in an answer below here..

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

提交回复
热议问题