首页 > 解决方案 > TypeScript 中的承诺

问题描述

我正在尝试在 TypeScript 中使用 Cloud Functions 做一些工作,但我遇到了 Promises 的问题。

const winnersObject = async (leagueId: string, round: string) : Promise<Object> => {
  return new Promise(async function(resolve, reject) { 
      const winners: { [key: string]: any} = {};
      return firestore
        .collection('matches')
        .where('leagueId', '==', leagueId)
        .where('round', '==', round)
        .where('status', 'in', finishedStatus)
        .get()
        .then((snapshot) => {
          if (snapshot.empty) { 
            console.log('No matches'); 
            reject(); 
          } //No hay partidos finalizados 
          else { 
            //Define winner
            snapshot.docs.forEach(async (doc) => {
              if (doc.data().awayScore === doc.data().homeScore) { console.log('Tie'); winners[doc.data().matchId] = 3; }
              else if (doc.data().homeScore > doc.data().awayScore) { console.log('Home win'); winners[doc.data().matchId] = 2; }
              else if (doc.data().awayScore > doc.data().homeScore) { console.log('Away win'); winners[doc.data().matchId] = 1; }
            });
            resolve(winners);
          }
        }).catch((e) => console.log(e));
  });
};

const getPicksDocuments = async (leagueId: string, round: string) : Promise<Array<Object>> => {
  return new Promise(async function(resolve, reject) {
      return firestore
        .collection('picks')
        .where('leagueId', '==', leagueId)
        .where('round', '==', round)
        .get()
        .then((snapshot) => {
          if (snapshot.empty) { 
            reject(); 
          } //No picks
          else { resolve(snapshot.docs); }
        }).catch((e) => console.log(e));
   });
};

当我尝试像这样调用这些函数时:

  const winners = await winnersObject(leagueId, round);
  console.log(winners, 'Finished matches');

我明白了{ undefined: 1 } 'Finished matches'

而在尝试的时候

  const allPicksDocs = await getPicksDocuments(leagueId, round);
  console.log(allPicksDocs.length, 'Picks documents');

我什至根本没有打印出来。

标签: javascripttypescript

解决方案


推荐阅读