javascript - 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');
我什至根本没有打印出来。
解决方案
推荐阅读
- c# - 如何在运行时更改 Process.Start 的目标?
- android - 使用 MvvmCross 和 FFImageLoading 的 Xamarin Android 可见性绑定问题
- java - 修复,使显示可以同时显示十进制数和整数 java
- reactjs - 路由刷新页面时显示空白页
- python - “?”在哪里?用于服务器端参数绑定的 Snowflake SQL 查询中的字符?
- javascript - 前端授权几乎总是不安全的。你不同意吗?
- python - Keras 模型 ValueError:无法挤压昏暗 [1],预期维度为 1,得到 90
- javascript - 将参数/变量保存到 JSON 文件中的不和谐帐户
- hybris - Hybris - 将服务产品添加到主要产品
- reactjs - 根据条件改变状态