javascript - 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 的东西,我试图搜索可能的重复项,但很难找到任何东西
解决方案
我想知道 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
}
推荐阅读
- json - 在 Python 中将 POST 响应转换为 Dictionary 时出错
- r - 在 R 中使用区间对数据进行分组
- java - Spring 与 JMS 的集成无法正常工作
- jsf - 如何在命令按钮单击时调用 index.xhtml 的中心布局中的页面?
- report - 在 BIRT 报告中使用 getLong() 时出错
- javascript - HTML 输入文件上传保存为非常长的 url,没有 PHP、AJAX 或 jQuery
- c++ - 调用未记录的函数
- service-worker - 使用 networkFirst 策略的 Workbox 回退响应
- c# - 使用 CefSharp 构建 x64 项目
- android - 使用 ffmpeg-android 连接视频文件