从node.js中的forEach返回以循环firebase结果
在我循环所有firebase结果以正确完成我的云功能后,如何获得回报从node.js中的forEach返回以循环firebase结果,node.js,firebase,foreach,promise,google-cloud-functions,Node.js,Firebase,Foreach,Promise,Google Cloud Functions,在我循环所有firebase结果以正确完成我的云功能后,如何获得回报 var count = 0; return ref.child('/records').once('value').then(snap=>{ snap.forEach(snapChild=>{ var ucName = ${snapChild.val().name.toUpperCase(); var update = {'name':ucName); ref
var count = 0;
return ref.child('/records').once('value').then(snap=>{
snap.forEach(snapChild=>{
var ucName = ${snapChild.val().name.toUpperCase();
var update = {'name':ucName);
ref.child(`/records/${snapChild.key}`).update(update).then(()=>{
count++;
res.write(`<p>${ucName} updated</p>`);
});
})
}).then(()=>{
return res.end(`<p>end of list (${count} records)</p>`);
})
它实际上执行了它应该执行的操作,但计数器保持在0,我得到一个错误“结束后写入”-我猜是因为forEach缺少返回值。这是因为在未处理快照子项时调用了最后一个then回调。您需要使用Arraymap生成承诺数组,并使用Promise.all等待所有承诺都未解决:
var count = 0;
return ref
.child('/records').once('value')
.then(snap => {
let ops = snap.map(snapChild => {
var ucName = ${snapChild.val().name.toUpperCase();
var update = {'name':ucName);
return ref.child(`/records/${snapChild.key}`).update(update).then(() => {
count++;
res.write(`<p>${ucName} updated</p>`);
});
});
return Promise.all(ops);
})
.then(()=>{
return res.end(`<p>end of list (${count} records)</p>`);
});
我有一个问题与你的问题无关@alexmac回答了这个问题。为什么要使用ES6 fat arrow而不使用const和let?你是对的-我应该使用ucName和update-毫无疑问。只是不太清楚计数-因为它不是“常数”;我需要在“完成”firebase、云功能、节点、nodeEmailer、把手、auth、Polymer、PWA之后阅读它;count是一个因count++而改变值的变量,它是一个let。另一方面,ucName和update不会被修改,它们是常量。祝这些技术人员好运:谢谢-我正走在承诺的道路上。但是我没有弄明白。谢谢你的解决方案。