javascript - 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")
}
});
});
解决方案
我有同样的行为,因为在 forEach 循环中执行所有迭代之前退出了我的云函数。我使用这段代码摆脱了它:
for (const doc of querySnapshot.docs) {
// Do wathever you want
// for instance:
await doc.ref.update(newData);
}
推荐阅读
- python - cvs 文件到 host.yaml 用于 Nornir
- json - GET 参数在 URL 中起作用,但在 Postman 中不作为正文
- c# - C#项目引用之谜
- c++ - 我的 C++ 函数给出了关于声明的异常错误
- android - Android 设备未收到通过 Firebase 云消息传递发送的 5% 的推送
- c - C/C++ VS 代码扩展引发构建错误:““C/C++”任务的任务提供程序意外提供了“shell”类型的任务。”
- ember.js - 如何在 Ember.JS 应用程序中加载 Require.JS 开发的模块?
- java - JAVA-JNA:我无法在整个回调函数中修改结构字段
- javascript - 如何通过单击 Web 浏览器中的按钮启动本地服务器
- python - 配置:错误:尝试使用 pyenv 安装 python 时,C 编译器无法创建可执行文件