Skip to content

Instantly share code, notes, and snippets.

@nielsvanvelzen
Created May 3, 2018 19:41
Show Gist options
  • Save nielsvanvelzen/3caa3749b8a6d8ff2eb87588819b0185 to your computer and use it in GitHub Desktop.
Save nielsvanvelzen/3caa3749b8a6d8ff2eb87588819b0185 to your computer and use it in GitHub Desktop.
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));
}
}
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