Home  >  Q&A  >  body text

Title rewritten to: "(ES6) Class (ES2017) Async/Await Getter Method"

<p>Is it possible or possible in the future to return a value from an ES6 class's getter via ES2017's await/async functions. </p> <pre class="brush:php;toolbar:false;">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');</pre> <p><br /></p>
P粉564192131P粉564192131395 days ago547

reply all(1)I'll reply

  • P粉025632437

    P粉0256324372023-08-23 11:52:11

    Update: As others have pointed out, this doesn't really work. @kuboon provided a nice solution below.

    You can do this

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

    This is the same as the code below

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

    reply
    0
  • Cancelreply