Is it possible to call an async function inside a constructor in react-native?
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`
});
}
Asynchronous constructor is a potential antipattern because it doesn't result in behaviour that is expected from it.
Asynchronous side effects are supposed to happen after a component is mounted and thus occur in componentDidMount
, this is what it's for. It's impossible to delay the lifecycle of a component and it's incorrect to think about it in these terms.
It's supposed to work like:
class Foo extends Component
async a() {...}
async componentDidMount() {
await this.a();
}
render() {
(conditionThatIsTrueWhenThereResult) ? (
<div>...the result from a...</div>
) : (
<div>fallback</div>
);
}
}
If it's necessary to keep a component synchronous, a
asynchronous side effect should be moved to parent component that renders a child only when the result from a
is ready to use.
Call a()
in componentDidMount like so:
async componentDidMount() {
await a();
otherFuncions()
}
otherFunctions()
will only be executed after a()
is completed