Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ES6 Async constructors
* 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));
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
You can’t perform that action at this time.