【问题标题】:Promise, async, await - Boolean returns false but if condition still gets calledPromise, async, await - Boolean 返回 false 但如果条件仍然被调用
【发布时间】:2021-10-01 20:29:37
【问题描述】:

上下文

我有这段代码来强制应用更新,它检查是否需要更新,并且应该根据用户应用的版本号与 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
    })
  }

问题

当用户应用的版本号相等/更高时,它不能正常工作。这是我使用上面的函数的函数。出于某种原因,即使函数的响应为假,逻辑也会执行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 的东西,我尝试搜索可能的重复项,但很难找到任何东西

【问题讨论】:

  • 这不是重点吗?您正在使用 NOT 运算符 (!),它将 false 转换为 true(反之亦然)。
  • @KelvinSchoofs 感谢您的回复!我进行了一些编辑以使其更清晰,但基本上我们只想运行代码并在不是最新版本时显示弹出窗口。
  • website 应该通过。不要依赖外部范围内的成员。通过它是微不足道的。

标签: javascript reactjs typescript react-native promise


【解决方案1】:

我想知道 TypeScript 怎么没有捕捉到这一点,但问题是你的函数返回一个 Promise&lt;void&gt; 而不是 Promise&lt;boolean&gt;。你从来没有 return 来自 isLatestVersion 的任何东西,所以它以 undefined 结束,你的反转条件总是运行 if 块。

根本问题在于awaiting a .then(…) chain - 您想使用thenreturn

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
}

【讨论】:

  • 是的!就是这样,但我认为您的意思是return !res.isNeeded。或者我可以将函数重命名为 isUpdateNeeded
  • @Saamer OP 有 if (res.isNeeded) { …; return true } else return false,我将其缩写为 return res.isNeeded,但没有更改功能。但是是的,你是对的,函数名没有意义。
  • 感谢您向我展示这两种方法的答案,可能会经常参考这个答案!
猜你喜欢
  • 2019-04-22
  • 2020-10-02
  • 2022-08-22
  • 2018-03-27
  • 2017-09-11
  • 2020-04-06
  • 1970-01-01
  • 2012-06-11
相关资源
最近更新 更多