(ES6) class (ES2017) async / await getter

2019-02-16 04:31发布

问题:

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

回答1:

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


回答2:

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.



回答3:

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