At the moment, I'm attempting to use async/await within a class constructor function. This is so that I can get a custom e-mail tag for an Electron project I'm working on.
customElements.define('e-mail', class extends HTMLElement {
async constructor() {
super()
let uid = this.getAttribute('data-uid')
let message = await grabUID(uid)
const shadowRoot = this.attachShadow({mode: 'open'})
shadowRoot.innerHTML = `
<div id="email">A random email message has appeared. ${message}</div>
`
}
})
At the moment however, the project does not work, with the following error:
Class constructor may not be an async method
Is there a way to circumvent this so that I can use async/await within this? Instead of requiring callbacks or .then()?
You can definitely do this, by returning an Immediately Invoked Async Function Expression from the constructor. IIAFE is the fancy name for a very common pattern that was required in order to use await outside of an async function, before top-level await became available:
(async () => {
await someFunction();
})();
We'll be using this pattern to immediately execute the async function in the constructor, and return its result as this:
// Sample async function to be used in the async constructor
async function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
class AsyncConstructor {
constructor(value) {
return (async () => {
// Call async functions here
await sleep(500);
this.value = value;
// Constructors return `this` implicitly, but this is an IIFE, so
// return `this` explicitly (else we'd return an empty object).
return this;
})();
}
}
(async () => {
console.log('Constructing...');
const obj = await new AsyncConstructor(123);
console.log('Done:', obj);
})();
To instantiate the class, use:
const instance = await new AsyncConstructor(...);
For TypeScript, you need to assert that the type of the constructor is the class type, rather than a promise returning the class type:
class AsyncConstructor {
constructor(value) {
return (async (): Promise<AsyncConstructor> => {
// ...
return this;
})() as unknown as AsyncConstructor; // <-- type assertion
}
}
super in the constructor of the derived class, you'll have to call it without await. If you need to call the super constructor with await, you'll run into TypeScript error 2337: Super calls are not permitted outside constructors or in nested functions inside constructors.Before using this solution, determine whether you'll need to extend the class, and document that the constructor must be called with await.
Because async functions are promises, you can create a static function on your class which executes an async function which returns the instance of the class:
class Yql {
constructor () {
// Set up your class
}
static init () {
return (async function () {
let yql = new Yql()
// Do async stuff
await yql.build()
// Return instance
return yql
}())
}
async build () {
// Do stuff with await if needed
}
}
async function yql () {
// Do this instead of "new Yql()"
let yql = await Yql.init()
// Do stuff with yql instance
}
yql()
Call with let yql = await Yql.init() from an async function.