我有一个名为async a()
的异步函数,它必须在函数componentDidMount()
之前运行.
那么,如何在构造函数中调用异步函数呢?
我需要确保我的async a()
首先在构造函数中完成,然后执行componentDidMount中的所有方法.
我有一个名为async a()
的异步函数,它必须在函数componentDidMount()
之前运行.
那么,如何在构造函数中调用异步函数呢?
我需要确保我的async a()
首先在构造函数中完成,然后执行componentDidMount中的所有方法.
你不能在构造器内部完成,因为构造器不能等待await
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`
});
}