首页 > 解决方案 > React Native - 异步等待的问题

问题描述

我有 2 个函数调用:

const result = _checkPermissions();
if (result === 'granted') {
    this._googleSignIn();
} 

我想_checkPermissions()在运行 if 语句之前返回.....但是我似乎无法做到这一点,代码只是继续执行 if 语句之前_checkPermissions()返回。

我知道它与异步等待有关,但我无法弄清楚

下面是代码_checkPermissions()

export const _checkPermissions = async () => {
  const result = await check(
    Platform.select({
      android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
    }),
  );
  switch (result) {
    case 'blocked':
      return 'blocked';
    case 'granted':
      return 'granted';

标签: javascriptreact-nativeasync-await

解决方案


你只需要等待_checkPermissions。因为它_checkPermissions是一个async函数,它返回一个承诺,该承诺在稍后的时间点解决/拒绝。您可以将 await 与 Promise 一起使用,也可以在 Promise.then块内写入。

承诺方法:

const result = await _checkPermissions();
if (result === 'granted') {
    this._googleSignIn();
} 
  • 如果你正在使用await你需要添加async到父函数。*

.then方法:

_checkPermissions().then(result => {
    if (result === 'granted') {
        this._googleSignIn();
    } 
})

推荐阅读