(ES6) class (ES2017) async / await getter

Ecmascript 6Async AwaitEcmascript 2017

Ecmascript 6 Problem Overview


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

Ecmascript 6 Solutions


Solution 1 - Ecmascript 6

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

Solution 2 - Ecmascript 6

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

Solution 3 - Ecmascript 6

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.

Solution 4 - Ecmascript 6

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`
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEnkiView Question on Stackoverflow
Solution 1 - Ecmascript 6FractalfView Answer on Stackoverflow
Solution 2 - Ecmascript 6kuboonView Answer on Stackoverflow
Solution 3 - Ecmascript 6BergiView Answer on Stackoverflow
Solution 4 - Ecmascript 6Hibou57View Answer on Stackoverflow