【发布时间】:2018-10-11 02:16:54
【问题描述】:
我在这里尝试做两件事。 1) 向所有员工发送通知。 2)将特定的参考复制到 员工 ID 参考。如果不存在特殊参考,我将复制一般参考。 该程序运行没有错误。事实上它的完美。但有时我会收到通知代码部分的超时错误。
错误:fcm.googleapis.com 网络超时。请再试一次。
将一个引用复制到另一个引用的代码始终有效,从未在那里收到错误。 我觉得这个错误是由于没有正确处理 forEach 的承诺。你能帮我让这段代码完美地执行,并正确放置 Promise 吗?
exports.myFunc = functions.https.onRequest( (request, response) => {
admin.database().ref('/Employees').once('value').then(function(snap) {
snap.forEach(function (snapshot) {
var obj = snapshot.val();
if(obj.department){//only go ahead if dept is present
console.log(' : ' + obj.department);
var id, tkid, dept;
id = obj.empId; tkid = obj.tokenId; dept = obj.department;
var welcomeStr="hello! Welcom to our Department";
//================================================================notifications
var payload = {
data: {
greeting: welcomeStr,
to_who: id
}
};
admin.messaging().sendToDevice(tkid,payload)
.then(function(response){
console.log("Successfully sent message: ", response);
})
.catch(function(error){
console.log("Error sending message: ", error);
})
//===================================================Ref copying
var destinationRef = admin.database().ref('/Employees/' + id);//final destination
var option2Ref = admin.database().ref('/Company/General');//when special doesnt exist
var option1Ref = admin.database().ref('/Company/Special');//if special exists
option1.once('value', function(snapshot1){
if (snapshot1.exists()){//copy from straing from option11 to Employees/id
option1.once('value', function(snap) {
destinationRef.set( snap.val(), function(error) {
if( error && typeof(console) !== 'undefined' && console.error ) { console.error(error); }
console.log('DONE .... ' + id);
});
});
}
else{//we need to copy from option2 to Employees/id
option2Ref.once('value', function(snap) {
newRef.set( snap.val(), function(error) {
if( error && typeof(console) !== 'undefined' && console.error ) { console.error(error); }
console.log('DONE .... ' + id);
});
});
}
});
}
else{
console.log('No Department: ' + obj.dept);
return;
}
});
});
response.send("WOKAY!");
});
【问题讨论】:
-
我相信您已经正确地确定了
forEach循环是您问题的核心——很可能,循环的每次迭代都会启动另一个未返回的承诺链——我想你再次经历了失信的承诺.. -
你其实是对的......有时日志会打印 2-3 次相同的结果。
标签: javascript node.js firebase firebase-cloud-messaging google-cloud-functions