Title rewritten to: "(ES6) Class (ES2017) Async/Await Getter Method"
P粉564192131
P粉564192131 2023-08-22 22:10:47
0
1
513

Is it possible or possible in the future to return a value from an ES6 class's getter via ES2017's await/async functions.

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


P粉564192131
P粉564192131

reply all (1)
P粉025632437

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

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); }); }) } }
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!