我有一个云功能,基本上是一个onCreate()
触发器。每当在我的CustomerRequest
节点中创建订单时,它就会触发。我正在使用此功能来检查我的工作站中的在线供应商,并将找到的第一个供应商分配给该订单。一切正常,但唯一的问题是在触发几秒钟后,此函数使用我之前下达订单的订单ID额外运行了2或3次。我想这与诺言有关。我是JavaScript新手,所以不知道它是如何工作的。
exports.processOrder = functions.database.ref('/CustomerRequests/{sid}/orders/{oid}')
.onCreate((snapshot, context) => {
const stationID = context.params.sid;
var oid = context.params.oid;
var uid = snapshot.child('uid').val();
//const Promises = [];
var getInstanceIdPromise;
var setSupPromise;
var driveStatusPromise;
var instanceID;
//send notification
var product = snapshot.child("products").val();
const payload = {
data:{
title: "You have got a new order",
oid: oid
}
};
var online = admin.database().ref('/STATION/'+stationID+'/SUPPLIERSONLINE')
.on("value", function(snapshot) {
console.log(snapshot.val());
snapshot.forEach(element => {
if(element.val() == "ONLINE"){
//get instance of that supplier
getInstanceIdPromise = admin.database().ref('/SUPPLIER/'+element.key+'/instid').on('value',function(snap){
instanceID = snap.val();
admin.messaging().sendToDevice(instanceID, payload)
.then(function (response) {
console.log("Successfully sent message:", response);
})
.catch(function (error) {
console.log("Error sending message:", error);
});
});
console.log("We are running");
setSupPromise = admin.database().ref('/CustomerRequests/'+context.params.sid+'/orders/'+context.params.oid).child('supplier').set(element.key);
//admin.database().ref('/SUPPLIER/'+element.key+'/orders').child(context.params.oid).set(true);
driveStatusPromise = admin.database().ref('/SUPPLIERLOCATION/'+element.key+'/drivestatus').set(0);
}
});
// return Promise.all([online,getInstanceIdPromise,setSupPromise,driveStatusPromise]);
},function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});