我有一个名为 async a()
的异步函数,它必须在函数 componentDidMount()
之前运行。
那么如何在构造函数中调用异步函数呢? 因为构造函数在 componentDidMount 函数之前运行。
我需要确保我的 async a()
首先在构造函数中完成,然后执行 componentDidMount 中的所有方法。
最佳答案
你不能在构造函数中执行它,因为构造函数不能等待 await
因此,对于要在 async a()
之后运行的所有进程,您可以使用另一个函数(例如 b()
)。您有两种选择:
1- 使用 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- 使用 .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`
});
}
关于javascript - 是否可以在 react-native 的构造函数中调用异步函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55025299/