Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to call an async function inside a constructor in react-native?

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.

like image 941
Iqbal Jan Avatar asked Mar 06 '19 14:03

Iqbal Jan


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.

How do you call async function in React Native?

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.

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 have an async function?

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.


1 Answers

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`
    });
}
like image 197
SiSa Avatar answered Oct 16 '22 11:10

SiSa