typescript - 如何及时获取打字稿异步函数的返回值
问题描述
我正在创建一个 Firebase 云函数,它依赖于一些关于实时数据库中是否存在某些键的数据,但它没有得到正确返回。
我尝试包装通过 async/await 关键字或直接构造 Promise 调用的函数,但它始终返回 undefined 或 Promise { }
async function checkMatchExists(baseUser: string, friend:string){
return await admin.database().ref('pairs/').child(baseUser).once("value",
snapshot => {
return snapshot.exists();
});
}
在主要功能中:
let matchExists;
if(checkMatchExists(userId, eachUserId)){
console.log("match exists in db!")
matchExists = true;
} else {
matchExists = false
console.log("match not here yet");
}
if(distance <= 0.0092 && !(userId === eachUserId) && !matchExists){
console.log("Match exists:");
console.log(matchExists);
}
我也尝试过直接插入checkMatchExists(userId, eachUserId)
if 语句,但无济于事。以下也只会产生 undefined :
(async () => {
console.log(checkMatchExists(eachUserId, userId));
})().then(result => {
console.log(result);
}).catch(error => {
console.error(error);
});
我尝试过的所有结果,undefined
或者Promise { <pending> }
但我需要实际结果。控制台确实返回"match exists in db!"
,但这只是因为如果将 Promise { } 评估为 true。我如何等待承诺解决?
编辑:事实证明我需要await
在另一种await
方法中进行调用。这在 TypeScript 中可行吗?
解决方案
异步函数总是返回一个承诺。您的代码看起来像是假设返回值始终是布尔值。由于异步函数总是返回一个 Promise,你应该使用await
或使用 then/catch 来确定 Promise 发生了什么。
const exists = await checkMatchExists(userId, eachUserId)
推荐阅读
- selenium - CreatePlatformSocket() 返回错误:提供的参数无效。(0x2726) 尝试通过网络路径访问 chromedriver
- android - ACTION_CANCEL 生成并丢失数据
- javascript - 在 php 中显示事件位置的天气条件
- ionic-framework - Ionic1 中的文件选择器
- android - 图像浏览错误
- elasticsearch - 使用 curator 插件从特定索引中删除旧文档
- python - 如何使用 pymodbus 从寄存器中读取
- php - 如何将 SOAP 响应转换为 XML 或 JSON 格式?
- python - 我怎样才能从这个块中提取最清晰、最清晰的设计?
- linux - 使用 awk 提取理想字符串