承诺与推力的消防站 [英] Firestore with promises and push

查看:46
本文介绍了承诺与推力的消防站的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢Frank在Firebase上的帮助我使用此代码.我在将文件ID推送到Friends集合下时遇到了这个问题.我不确定在下面的代码中将const friendIdconst accepted推送到friendsList数组的最佳方法是什么.

Thanks to Frank over at Firebase for helping me with this code. I just had this one issue with pushing the document id under Friends collection. I am not sure what is the best way to push const friendId and const accepted to friendsList array in the code below.

const db = admin.firestore();
const friendRef = 
db.collection('users').doc(id).collection('friends');

friendRef.get().then((onSnapshot) => {
  var promises = [];

  onSnapshot.forEach((friend) => {
    const personId = String(friend.data().person_id);
    const friendId = String(friend.id);
    const accepted = friend.data().accepted;

    promises.push(db.collection('users').doc(personId).get());
  });

  Promise.all(promises).then((snapshots) => {
    friendsList = [];
    snapshots.forEach((result) => {
      friendsList.push({
        friendId: friendId,
        accepted: accepted,
        firstName: result.data().name.first,
        lastName: result.data().name.last,
      });
    });
    res.send(friendsList);
  });
}).catch((e) => {
  res.send({
    'error': e
  });
})

我尝试了一些尝试,但是没有成功.任何帮助将不胜感激.

I tried a few things, but it didn't work. Any help would be appreciated.

推荐答案

问题在于,对于每个friend值,您将promises数组中的值从调用db.collection('users').doc(personId).get()中推入.而且,除了作为局部变量之外,您永远不会为每个朋友保留personIdfriendIdaccepted的值.

The problem is that you push in the promises array what you get from the calls db.collection('users').doc(personId).get() for each friend value. And you never keep values of personId, friendId, accepted for each friend except as local variables.

您应遵守所有承诺.为此,您可以像这样返回自定义Promise.

You should keep them in every array of promises. For this you can return custom Promise like this.

promises.push(new Promise((resolve, reject) => {
    db.collection('users').doc(personId).get()
    .then(docResult => {
        resolve({         
            friendId: friendId,
            accepted: accepted,
            doc: docResult
        });
    })
    .catch(reason => {
        reject(reason);
    });
});

,然后在迭代快照数组时:

and then when you iterate snapshots array:

snapshots.forEach((result) => {
    friendsList.push({
        friendId: result.friendId,
        accepted: result.accepted,
        firstName: result.doc.data().name.first,
        lastName: result.doc.data().name.last,
    });
});

这篇关于承诺与推力的消防站的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆