内部的Firestore内部承诺forEach,在外部承诺之后执行

时间:2018-12-26 13:37:28

标签: javascript node.js firebase google-cloud-firestore

我正在使用node.js从Firestore中的2个不同集合中获取数据。

此问题与此类似,但是没有以下问题的答案:Nested Firebase Firestore forEach promise queries

就我而言,我正在创建一个类似instagram的应用,其中有一个“时间轴”集合。在时间轴文档中,我有一个用户密钥。通过该用户密钥,我想从“用户”集合中执行另一个查询。

从逻辑上讲,这里是查询步骤:

  1. 获取包含用户密钥的时间轴数据(在数组中)。
  2. 使用该用户密钥,获取用户数据(单个数据)
  3. 将JSON响应返回给客户端。

问题是,在获取用户数据之前会返回JSON响应。

这是我的代码:

tlRoute.get((req,res)=>{

  //reading from firestore
  let afs = req.app.get('afs');

  var timelineArr = [];

  let timelineRef = afs.collection(`timeline/${req.params.key}/timeline`);
  timelineRef.get().then((snapshot) => {

    snapshot.forEach((doc) => {

      if(!doc.exists){
        console.log('No such document!');
      } else {

        //populating timelineData with doc.data()
        console.log('populating timelineData');
        let timelineData = doc.data();

        let userRef = afs.doc(`user/${doc.data().userKey}`);
        userRef.get().then((doc) => {

          //adding user details to timelineData
          console.log('adding user details to timelineData');
          timelineData.profileImageUrl = doc.data().profileImageUrl;
          timelineData.username = doc.data().username;
          timelineArr.push(timelineData);

        });
      }

    });
  })
  .catch(err => {
    console.log(err);
  });

  console.log('this is the final timelineArr', timelineArr);

  //returning response json data to client
  return res.json(timelineArr);

});

在控制台日志中,这是我得到的日志:

this is the final timelineArr []
populating timelineData
populating timelineData
adding user details to timelineData
adding user details to timelineData

任何帮助将不胜感激。

3 个答案:

答案 0 :(得分:1)

我试图重构您的代码以产生相同的输出,添加了一些方法,每个方法都具有与一种特定类型的对象有关的更简单,隔离,可测试的目的。

// return a promise that resolves to a user doc snapshot with the given key
function getUserWithKey(db, userKey) {
  return db.doc(`user/${userKey}`).get();
}

// return a promise that resolves to a timeline object augmented to include
// its doc id and its associated user's username
function timelineObject(db, timelineDocSnapshot) {
  let timelineObject = timelineDocSnapshot.data();
  timelineObject.postKey = timelineDocSnapshot.id;
  return getUserWithKey(db, timelineObject.userKey).then(userDocSnapshot => {
    timelineObject.username = userDocSnapshot.data().username;
    timelineObject.profileImageUrl = userDocSnapshot.data().profileImageUrl;
    return timelineObject;
  });
}

// return a promise that resolves to all of the timeline objects for a given key
function getTimeline(db, key) {
  let timelineRef = db.collection(`timeline/${key}/timeline`);
  return timelineRef.get().then(querySnapshot => {
    let promises = querySnapshot.docs.map(doc => timelineObject(db, doc));
    return Promise.all(promises);
  });
}

// get route for a timeline
tlRoute.get((req,res)=>{
  let db = req.app.get('db');
  let key = req.params.key;
  return getTimeline(db, key).then(timelineObjects => {
    return res.json(timelineObjects);
  });
})

可以使用async / await语法进一步改进此代码。

答案 1 :(得分:0)

Sooo Firebase使用回调或Promise(“。then((snapshot)=> {})” thing),该方法在从Firestore检索数据之后运行。您正在做的是在运行回调方法之前,因此在使用Firestore的数据填充之前,返回timelineArr!

对此的一种解决方案是将return语句移到回调方法内部,并使整个函数异步。会是这样的:

var timelineArr = [];
async function RetrieveData() {
    let timelineRef = afs.collection(`timeline/${req.params.key}/timeline`);
    await timelineRef.get().then((snapshot) => {

    snapshot.forEach((doc) => {

      if(!doc.exists){
        console.log('No such document!');
      } else {

        //populating timelineData with doc.data()
        console.log('populating timelineData');
        let timelineData = doc.data();

        let userRef = afs.doc(`user/${doc.data().userKey}`);
        userRef.get().then((doc) => {

          //adding user details to timelineData
          console.log('adding user details to timelineData');
          timelineData.profileImageUrl = doc.data().profileImageUrl;
          timelineData.username = doc.data().username;
          timelineArr.push(timelineData);

        });
      }

    });

      //returning response json data to client
      return res.json(timelineArr);

    }).catch(err => {
      console.log(err);
    });
}

RetrieveData()

console.log('this is the final timelineArr', timelineArr);

祝你好运!

最诚挚的问候,Eskils。

答案 2 :(得分:0)

我决定使用for来遍历内在的诺言。

这是我的代码:

tlRoute.get((req,res)=>{

  let db = req.app.get('db');
  let key = req.params.key;

  var timelineArr = [];

  getData(db, key, timelineArr).then(results => {

    for (let index = 0; index<results.length; index++) {
      timelineArr[index].profileImageUrl = results[index].data().profileImageUrl;
      timelineArr[index].username = results[index].data().username;
    }
    console.log(results.length);

    console.log(timelineArr);

    console.log('this is the final timelineArr');
    //returning response json data to client 
    return res.json(timelineArr);

  });

});

function getData(db, key, timelineArr){
  let timelineRef = db.collection(`timeline/${key}/timeline`);
  return timelineRef.get().then((snapshot) => {

    console.log('snapshot length: ', snapshot.length);

    var promiseArr = [];

    snapshot.forEach((doc) => {

      if(!doc.exists){
        console.log('No such document!');
      } else {

        //populating timelineData with doc.data()
        console.log('populating timelineData');
        let timelineData = doc.data();
        timelineData.postKey = doc.id;
        timelineArr.push(timelineData);

        console.log('userKey: ', doc.data().userKey);
        let userRef = db.doc(`user/${doc.data().userKey}`);
        promiseArr.push(userRef.get());

      }
    });
    return Promise.all(promiseArr);

  })
  .catch(err => {
    console.log(err);
  });
}