javascript - 是否可以在 react-native 的构造函数中调用异步函数?

标签 javascript reactjs react-native asynchronous

我有一个名为 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/

相关文章:

javascript - 了解 $.ajax() 和 $.ajax().then 之间的区别

javascript - 如何从另一个js文件访问react组件中定义的变量?

reactjs - Jest 在测试运行完成后一秒钟没有退出

android - 从 uri 加载失败响应时的缩略图 - React Native

javascript - 在 JavaScript 中使用 new 运算符声明函数有什么好处?

javascript - 从转译中排除箭头函数

javascript - 如何在相应的滚动条上获得虚线 svg 动画?

css - 从 MUI 设计 DatePicker 的样式

java - 如何从reactjs应用程序调用java类

android - 循环一个 React-Native UI 组件