我正在尝试为firebase创建一个云功能,根据延迟值删除用户,并在延迟次数后插回.
exports.delayqueue = functions.database.ref('/queues/{queueid}/members/{memberid}').onWrite(event => { var members = event.data.ref.parent; var user = event.data; var queueid = members.parent; var userid = event.params.memberid; var delayfor = user.child('delay').val(); var name = user.child('name').val(); if(delayfor != 0){ members.child(event.params.memberid).remove(); join(userid,queueid,delayfor,name); return; }else{ return; } }); function join(userid,name){ setTimeout(function(){ var ref = db.ref("queues/queueid/members/userid"); ref.set({ name: name,timestamp: Date.now(),delay : 0 }); },delayfor*1000); };
但是有人帮忙不行吗?
解决方法
你需要将你的setTimeout包装在一个Promise中:
exports.delayqueue = functions.database.ref('/queues/{queueid}/members/{memberid}').onWrite(event => { var members = event.data.ref.parent; var user = event.data; var queueid = members.parent; var userid = event.params.memberid; var delayfor = user.child('delay').val(); var name = user.child('name').val(); if (delayfor !== 0){ members.child(event.params.memberid).remove(); return join(userid,name); } else { return; } }); function join(userid,name){ return new Promise((resolve,reject) => { setTimeout(function(){ var ref = db.ref("queues/queueid/members/userid"); ref.set({ name: name,delay : 0 }).then(resolve,reject); },delayfor*1000); }); };
请注意,等待setTimeout所花费的时间将作为函数执行时间计费,并且还受函数超时的影响.如果你只是延迟几秒钟,那可能没问题,但如果延迟预计是几分钟,那么这个解决方案就不可行或具有成本效益.