I have an async function named async a()
which has to be run before function componentDidMount()
.
So how can I call an async function inside a constructor? Because the constructor function gets run before the componentDidMount function.
I need to be sure my async a()
completes first in the constructor and then all methods within componentDidMount are executed.
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.
Async keyword use for define function for use await task, when you want to use to await for wait task then first you have to define async function. Await keyword use for stop execution till task response, we will use multiple await calls in one async function.
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.
Async Option ConstructorThe async function call can be added right into the class instantiation step, without needing a separate init() call or having to modify your established method of class construction.
You can't do it inside constructor, because constructor can't wait for await
So you can have another function(for example b()
) for all the processes you want to run after async a()
. And you have two choice for doing this:
1- use async/await
:
async componentDidMount() {
try {
await a(); // it will wait here untill function a finishes
} catch(err) {}
b(); // after function a finished, this function will calls
}
2- using .finally
:
componentDidMount() {
// in below line, function `a` will call, and when it finishes, the function inside `.finally` will be notified
a().finally(() => {
b(); // now your function `a` finished and you can call extra process in function `b`
});
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With