首页 > 解决方案 > Promise, async, await - Boolean 返回 false 但如果条件仍然被调用

问题描述

语境

我有这段代码来强制应用程序更新,它检查是否需要更新,并且应该根据用户应用程序的版本号与 App Store 版本返回真或假。当用户应用程序的版本号较低时,这似乎可以正常工作,因为它将正确的 url 存储在website变量中:

  let website = ''
  const isLatestVersion = async (): Promise<boolean> => {
    await VersionCheck.needUpdate({
      packageName: 'com.tfp.numberbomb',
    }).then((res) => {
      if (res.isNeeded) {
        website = res.storeUrl
        return true // open store if update is needed.
      } else return false
    })
  }

问题

当用户应用的版本号为equal/higher时,它不能正常工作。这是我使用上面的函数的函数。showPopup()由于某种原因,即使函数的响应为假,逻辑也会执行。我究竟做错了什么?:

  const handleBiometricLogin = async () => {
    if (!(await isLatestVersion())) {
      await showPopup()
      return
    }
    ... // rest of the logic that doesn't run even when it's supposed to because of the return statement

附加信息

showPopup()功能仅供参考:

const showPopup = async () => {
    Alert.alert(
      translations['errors.login.update.title'] ?? 'Download Available',
      translations['errors.login.update.body'] ??
        'There is a new download available on the app store. Please update to gain access',
      [
        { text: translations['form.no-answer'] ?? 'No' },
        {
          text: translations['form.yes-answer'] ?? 'Yes',
          onPress: () => handleOpenLink(website, translations),
        },
      ],
    )
  }

我觉得我正在正确地执行 async 和 await 的东西,我试图搜索可能的重复项,但很难找到任何东西

标签: javascriptreactjstypescriptreact-nativepromise

解决方案


我想知道 TypeScript 是如何没有捕捉到这一点的,但问题是你的函数返回的是 aPromise<void>而不是 a Promise<boolean>。你从来没有return任何东西isLatestVersion,所以它以 结束undefined,你的倒置条件总是运行if块。

根本问题是await.then(…)then-你想使用andreturn

const isLatestVersion = (): Promise<boolean> => {
//                     ^ no async
  return VersionCheck.needUpdate({
//^^^^^^
    packageName: 'com.greenshield.mobileclaims',
  }).then((res) => {
    console.log(res)
    return res.isNeeded
  })
}

或仅await

const isLatestVersion = async (): Promise<boolean> => {
  const res = await VersionCheck.needUpdate({
//            ^^^^^
    packageName: 'com.greenshield.mobileclaims',
  });
//  ^ no .then()
  console.log(res)
  return res.isNeeded
}

推荐阅读