如何确保功能的执行有序? [英] How to ensure that the execution of functions are in order?

查看:66
本文介绍了如何确保功能的执行有序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个HTTP触发的函数,该函数在每次调用端点时都返回一个递增数.代码如下:

I have a HTTP-triggered function which returns an increment number every time the endpoint is called. The code looks like this:

export const reserve = functions.https.onRequest((req, resp) => {
  cors(req, resp, async () => {
    if (req.method.toLowerCase() !== 'post') {
      resp.status(405);
      resp.end();
    } else {
      const path = `counter`;
      const ref = firebase.database().ref(path);
      const oldCount = (await ref.once('value')).val();
      await ref.set(oldCount + 1);
      resp.status(200).send({
        number: oldCount
      });
      resp.end();
    }
  });
});

问题是,如果两个调用彼此非常接近,则该函数是否有可能返回相同的数字?如果是这样,是否有办法防止这种情况发生?

The problem is, if 2 invocations are very close to each other, is there a chance that the function can return the same number? If so, is there a way to prevent this?

推荐答案

是的,您是对的,可能会有这样的问题.我对Firebase并不熟悉,但是正在寻找可以让您直接在Firebase中增加该数字而不必先获取它的东西.这将是一项原子操作,并确保您不会遇到所描述的问题.

Yes, you are right, there can be an issue like this. I am not familiar with firebase but look for something that allows you to directly increment that number in firebase without having to fetch it first. This will be an atomic operation and ensure that you don't encounter the issue you described.

如果使用Firebase无法做到这一点,则可能必须在中间设置服务器,以某种方式保留计数器的记录.每次您要增加/减少数字时,请求都会通过您的服务器,该服务器首先在缓存上执行操作,然后通过调用Firebase API来完成请求.

If this is not possible with firebase then you might have to setup a server in the middle that somehow keeps the record of the counter. Each time you want to increment/decrement the number, the request goes through your server which performs the operation on the cache first and then completes the request by calling the Firebase API.

更新: 这是 Firebase建议的方式:

ref.transaction(function (current_value) {
  return (current_value || 0) + 1;
});

这篇关于如何确保功能的执行有序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆