如何在forEach循环中调用异步函数

时间:2019-04-03 15:10:43

标签: javascript google-cloud-firestore google-cloud-functions

我正在通过建立基本的社交网络来自学Firestore。当用户添加“帖子”时,我想将帖子添加到用户的“ Profile_Post”子集合中,然后在“后续”集合中循环浏览所有其他用户的关注者,并将帖子添加到其各自的流子集合中。

我尝试了以下代码,但不幸的是收到了只能在异步函数中调用await表达式的错误。

import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin';
// import { Timestamp } from '@google-cloud/firestore';
admin.initializeApp();
var db = admin.firestore();


exports.addPostToProfileAndUserStream = functions.firestore
    .document(`posts/{docID}`)
    .onCreate(async (snap, context) => {
        const postID: string = context.params.docID;
        const goalText: string = snap.data().goalText;
        const goalType: string = snap.data().goalType;
        const post: string = snap.data().post;
        const timePosted: admin.firestore.Timestamp = snap.data().timePosted;
        const url: string = snap.data().url;
        const user: string = snap.data().user;

        await admin.firestore().doc(`profile_posts/${user}/posts/${postID}`).set({

            goalText: goalText,
            goalType: goalType,
            post: post,
            timePosted: timePosted,
            url: url,
            user: user,


        });

        const followersRef = db.collection(`following/${user}/user_following`);
        const myFollowers = followersRef.get()
            .then(snapshot => {
                snapshot.forEach(doc => {
                    await admin.firestore().doc(`streams/${doc.id}/posts/${postID}`).set({

                        goalText: goalText,
                        goalType: goalType,
                        post: post,
                        timePosted: timePosted,
                        url: url,
                        user: user,


                    });

                });
            })
            .catch(err => {
                console.log('Error getting documents', err);
            });

    });

当我自己拥有帖子时,将帖子添加到“ profile_posts”子集合的第一个功能就可以正常工作。我想知道如何正确地在每个追随者之间循环,并呼叫await。

0 个答案:

没有答案