首页 > 解决方案 > 如何及时获取打字稿异步函数的返回值

问题描述

我正在创建一个 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 中可行吗?

标签: typescriptfirebasefirebase-realtime-databasegoogle-cloud-functions

解决方案


异步函数总是返回一个承诺。您的代码看起来像是假设返回值始终是布尔值。由于异步函数总是返回一个 Promise,你应该使用await或使用 then/catch 来确定 Promise 发生了什么。

const exists = await checkMatchExists(userId, eachUserId)

推荐阅读