(ES6) class (ES2017) async / await getter

Enki picture Enki · Nov 23, 2015 · Viewed 37.2k times · Source

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 result = await someAsyncOperation();

        return result;
    }
}

function someAsyncOperation() {
    return new Promise(function(resolve) {
        setTimeout(function() {
            resolve('baz');
        }, 1000);
    });
}

var foo = new Foo();

foo.bar.should.equal('baz');

Answer

Fractalf picture Fractalf · Sep 8, 2016

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