我有一个名为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`
    });
}

React-native相关问答推荐

单击时更改ToucheableOpacity colored颜色 不起作用

如何在react-navigation 中将drawer抽屉放在标题上?

Eslint 错误,configuration for rule "import/no-cycle" is invalid

警告:API 'variant.getMergeAssets()' 已过时 / Android Studio 3.3

如何在react-native中淡化视图的边缘?

Invariant Violation:requireNativeComponent: "RNCWebView" was not found in the UIManager

中彼此相邻对齐(Align) react native

修复错误:路由 'Home' 的组件必须是 React 组件

react-native 从右到左

Typescript:onPress 类型

Rich ReactNative TextInput

react-native Bottom Up drawer

ENOENT: no such file or directory, 打开 'android/app/src/main/assets/index.android.bundle'

React Native 得到这个错误'Unrecognized operator abs'

> 任务 :app:checkDebugAarMetadata 在运行 react-native run-android 时失败

React Native Build Error on IOS - typedef 用不同类型重新定义('uint8_t'(又名'unsigned char')与'enum clockid_t')

列之间的 React Native FlatList 分隔符

在 React Native 中将props传递给外部样式表?

xcode 使用错误的 node.js 版本

NavigationActions.reset 不是函数吗?