Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can async/await be used in constructors?

As the question stated. Will I be allowed to do this:

class MyClass {     async constructor(){         return new Promise()     } } 
like image 560
wintercounter Avatar asked Apr 01 '16 18:04

wintercounter


People also ask

Can we call async method in constructor?

The problem arises when you're trying to call such an asynchronous method from a class constructor: you can't use the await keyword inside the constructor. As long as you're only using methods which don't return a value, you can get away with it by just calling them without await, but that's not the right way to do it.

Can you have an async constructor JS?

The static async factory function pattern allows us to emulate asynchronous constructors in JavaScript. At the core of this pattern is the indirect invocation of constructor . The indirection enforces that any parameters passed into the constructor are ready and correct at the type-level.

Can a class be async?

Asynchronous learning allows you to learn on your own schedule, within a certain timeframe. You can access and complete lectures, readings, homework and other learning materials at any time during a one- or two-week period. “A big benefit to asynchronous classes is, of course, the flexibility.

Can I use async await instead of promises?

Async/Await is used to work with promises in asynchronous functions. It is basically syntactic sugar for promises. It is just a wrapper to restyle code and make promises easier to read and use. It makes asynchronous code look more like synchronous/procedural code, which is easier to understand.


1 Answers

To expand upon what Patrick Roberts said, you cannot do what you are asking, but you can do something like this instead:

class MyClass {   constructor() {      //static initialization   }    async initialize() {      await WhatEverYouWant();   }    static async create() {      const o = new MyClass();      await o.initialize();      return o;   } } 

Then in your code create your object like this:

const obj = await MyClass.create(); 
like image 86
Dave P. Avatar answered Sep 18 '22 05:09

Dave P.