如何及时获取打字稿异步函数的返回值

时间:2019-01-28 18:36:21

标签: typescript firebase firebase-realtime-database google-cloud-functions

我正在创建一个Firebase Cloud Function,它依赖于有关某些键在实时数据库中是否存在的数据,但是没有得到正确的返回。

我尝试包装通过async / await关键字或直接构造Promise调用的函数,但是它始终返回未定义或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语句中,但无济于事。以下也会产生未定义的内容:

(async () => {
      console.log(checkMatchExists(eachUserId, userId));
 })().then(result => {
      console.log(result);
 }).catch(error => {
      console.error(error);
 });

我在undefinedPromise { <pending> }中尝试过的所有结果,但我需要实际的结果。控制台会返回"match exists in db!",但这仅是因为如果Promise {}被评估为true。我如何等待诺言解决?

编辑:事实证明,我需要在另一个await方法中进行一个await调用。在TypeScript中可以吗?

1 个答案:

答案 0 :(得分:1)

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

const exists = await checkMatchExists(userId, eachUserId)