如何在firebase云函数中使用javascript

如何在firebase云函数中使用javascript

本文介绍了如何在firebase云函数中使用javascript setTimeout函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为 firebase 创建一个云函数,该函数根据延迟值删除用户并在延迟数之后插入回.

I'm trying to create a cloud function for firebase that remove a user depending on the delay value and insert back the after the number of delay.

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,queueid,delayfor,name){
  setTimeout(function(){
   var ref = db.ref("queues/queueid/members/userid");
    ref.set({
    name: name,
    timestamp: Date.now(),
    delay : 0
    });
   }, delayfor*1000);
   };

但它不起作用,有人可以帮忙吗?

But it's not working can someone help?

推荐答案

您需要将 setTimeout 包装在 Promise 中:

You'll need to wrap your setTimeout in a 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,queueid,delayfor,name);
  } else {
    return;
  }
});

function join(userid,queueid,delayfor,name){
  return new Promise((resolve, reject) => {
    setTimeout(function(){
      var ref = db.ref("queues/queueid/members/userid");
      ref.set({
        name: name,
        timestamp: Date.now(),
        delay : 0
      }).then(resolve, reject);
    }, delayfor*1000);
  });
};

请注意,等待 setTimeout 所花费的时间计费为函数执行时间,并且还受函数超时的影响.如果您只是延迟几秒钟,那可能没问题,但如果预计延迟是几分钟,那么这个解决方案将不可行或不划算.

Note that the time spent waiting for setTimeout is billed as function execution time and is also subject to the function timeout. If you're only delaying a few seconds, that might be okay, but if the delay is expected to be minutes this solution isn't going to be viable or cost-effective.

这篇关于如何在firebase云函数中使用javascript setTimeout函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 16:04