首页 > 解决方案 > ForEach 仅循环遍历 DataSnapshot 上的第一项

问题描述

我正在尝试遍历 DataSnapshot 的内容,然后根据条件为每个元素做一些工作,但目前,ForEach 只在第一项中做工作。“serverStatus”有时正在等待,有时在“onCall”中。当第一个项目是“onCall”时,不会像我认为应该做的那样遍历其余项目。下面是我从哪里获取信息的快照:

在此处输入图像描述

这是我的功能:

exports.manageCallRequests = functions.database.ref('/resquests/{userId}').onCreate((snap, context) => {
    const event = snap.val();

    console.log("function manageCallRequests is being called")
    var rootPath = admin.database().ref();
    var userOnCall = context.params.userId;

    var serversRef = rootPath.child('servers');
     var callRequest = event;
     var userTime = callRequest["time"];
     var waiting= "waiting";

  //We first get all the servers in ascending order depending on the last time they were used
  var serversSorted = serversRef.orderByChild('lastTimeUsed')


       //Gets the children on the "serversSorted" Query
       return serversSorted.once("value").then(allServers =>{
        //Checks if there is any child
            if(allServers.hasChildren()){



                    allServers.forEach(async function(server) {


                        //we extract the value from the server variable, this contains all the information 
                        //about each one of the servers we have
                        var serverInfo = server.val();
                        var serverKey = server.key;
                        var serverNumber = serverInfo["serverNumber"];
                        var serverStatus = serverInfo["serverStatus"];

console.log("server status "+serverStatus)
                        if(serverStatus === waiting){

                            const setCallRequest = await serversRef.child(serverKey).child("current").child("callRequest").set(callRequest);
                            const removeUserOnCall = await rootPath.child("resquests").child(userOnCall).remove();
                            const setServerStatus = await serversRef.child(serverKey).child("serverStatus").set("onCall");

                        }

                    });
                }else{
                    console.log("No servers available")


                }
            });

});

标签: javascriptnode.jsfirebase-realtime-databasegoogle-cloud-functions

解决方案


我有同样的行为,因为在 forEach 循环中执行所有迭代之前退出了我的云函数。我使用这段代码摆脱了它:

for (const doc of querySnapshot.docs) {
    // Do wathever you want    
    // for instance:
    await doc.ref.update(newData);
}

推荐阅读