首页 > 解决方案 > 在下一个命令之前完成整个循环/forEach

问题描述

我一直在工作,直到我在 forEach 之后添加了更多命令。基本上,当帖子被删除时,主要目标是将其从用户的提要中删除(这是有效的)。然后我将 4 .then() 链接起来,现在它只循环一次然后完成其余的过程......我怎样才能确保它在继续之前循环整个集合?

这是我的代码的样子:

    exports.updateFeedDelete = functions.database.ref('/categories/{postId}')
      .onDelete((snapshot, context) => {

      //...

      const followersRef = admin.database().ref(`friends/${friendId}`);

      return followersRef.once("value", function(snap) {
        snap.forEach(function(childSnapshot) {
          const followerId = childSnapshot.key;
          //FINISH ALL LOOPS HERE?
          return admin.database().ref(`feed/${followerId}/${postId}`).remove();
        });
      })
      //DONT EXECUTE UNTIL ALL LOOPS ARE DONE, NOT ONLY 1...
      .then(() => {
        //...
      })
      .then(() => {
        //...
      })
      .then(() => {
        //...
      })
      .then(() => {
        //...
    })

我很感激我能得到的所有帮助,干杯!

标签: node.jsfirebaseloopsforeachgoogle-cloud-functions

解决方案


如果您想知道一大堆并行操作何时完成,请使用数据库上的 Promise 接口为每个操作获取一个 Promise,并使用它Promise.all()来监视一组 Promise 并告诉您它们何时完成,然后开始其余的操作当您的代码Promise.all()告诉您一切都已完成时。

我真的不知道firebase API,但是从文档中的一点点看,我认为它可能看起来像这样:

exports.updateFeedDelete = functions.database.ref('/categories/{postId}')
  .onDelete((snapshot, context) => {

  //...

  const followersRef = admin.database().ref(`friends/${friendId}`);

  return followersRef.once("value").then(snap => 
    let promises = [];
    snap.forEach(childSnapshot => {
      const followerId = childSnapshot.key;
      // do whatever else here.  If asynchronous, chain promises
      // so you're pushing one promise into the array that
      // represents when all this code is done
      promises.push(admin.database().ref(`feed/${followerId}/${postId}`).remove());
    });
    return Promise.all(promises);                                     
  }).then(() => {
    // code here will run after the snap.forEach() code is done
  }).catch(err => {
    // handle errors here
  });
})

推荐阅读