Created
May 3, 2018 19:41
-
-
Save nielsvanvelzen/3caa3749b8a6d8ff2eb87588819b0185 to your computer and use it in GitHub Desktop.
ES6 Async constructors
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Ecmascript supports the `async` keyword to make functions async. | |
* Unfortunately it doesn't work on construcors. | |
* | |
* However: you can return in a constructor! | |
*/ | |
(async() => { // for top level await | |
class Example { | |
// ES6 constructor | |
constructor() { | |
// Return a promise | |
return this.construct() // our async function | |
.then(self => self || this); // make sure we return something, if our `construct()` implementation returns nothing (undefined) use `this` | |
} | |
// our "actual" constructor | |
async construct() { | |
// return a promise that resolved after 1 second | |
// this could for example retrieve information from an http api instead | |
await new Promise(resolve => setTimeout(resolve, 1000)); | |
} | |
} | |
console.time('construct'); | |
await new Example(); | |
console.timeEnd('construct'); // Will print about 1 second (1000ms) | |
})(); // for top level await |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment