在助手功能中拆分云功能并异步等待

时间:2019-08-22 20:33:55

标签: typescript firebase asynchronous google-cloud-functions

我有一个http触发的Google云功能,该功能返回给定用户的一些统计信息。 由于其他云功能也应使用从Firestore数据库中获取的统计信息,因此我想将其拆分为帮助程序功能。看起来像这样:

async function getStatsForUser(userId: string) {
    console.log(userId); // printed properly
    const stats = {};

    const docs = await admin.firestore().collection('stats')
        .where('user', '==', userId)
        .orderBy('key', 'desc').limit(1).get();

    docs.forEach(doc => {
        stats["key"] = doc.data().value;
        console.log("stats", stats); // this is never printed
        return stats;
    });
}

http云功能(目前仅用于测试)是这样的:

export const getStats = functions.https.onRequest(async (request, response) => {

    const userId = request.query.userId;

    try {
        const stats = await getStatsForUser(userId);
        console.log("stats2", stats); // printed but empty
        response.send(stats); // nothing is received on client site

    } catch (error) {
        console.log(error);
        response.status(500).send(error);
    }
});

因此日志输出如下:

userId abcdef...
stats2

因此,在等待异步帮助程序之前,云功能将以某种方式返回。 我知道我在async / await上遇到一些问题,但是我无法使其正常工作。我在做什么错了?

1 个答案:

答案 0 :(得分:4)

如果您的foreach循环未打印任何内容,则意味着您的docs结果中没有匹配的文档。

stats2日志状态中的

stats始终是不确定的,因为getStatsForUser从不返回任何内容。在foreach循环内返回值不会从函数中返回该值。它只是从传递给foreach的函数中返回一个值,该值不会传播到getStatsForUser之外。该函数getStatsForUser需要具有一个顶级return语句,该语句具有要返回的值。尝试在foreach循环中将结果累加到顶层定义的某个变量中,然后返回该变量。