如何保证函数的执行是有序的?

How to ensure that the execution of functions are in order?

我有一个 HTTP 触发的函数,它 return 每次调用端点时都会增加一个数字。代码如下所示:

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();
    }
  });
});

问题是,如果 2 个调用彼此非常接近,函数是否有可能 return 相同的数字?如果是这样,有什么办法可以防止这种情况发生吗?

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

如果使用 firebase 无法做到这一点,那么您可能必须在中间设置一个服务器,以某种方式保存计数器的记录。每次你想要 increment/decrement 这个数字时,请求都会通过你的服务器,它首先对缓存执行操作,然后通过调用 Firebase API.

来完成请求

更新: 这是 Firebase recommends this:

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