解析服务器原子增量结果 [英] Parse server atomic increment result

查看:84
本文介绍了解析服务器原子增量结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Parse后端中,我有一个包含唯一数字代码的数组,因此用户一定不能两次获得相同的代码.因此,我要在该表的某个列中保留一个索引.

In my Parse backend I have an array that contains unique number codes, so users must not be able to get the same code twice. For that reason somewhere in a column of some table I am keeping an index to this array.

现在有一个非常简单的操作-用户要求一个唯一的代码.云函数递增索引的当前值,并在新索引处返回数组的值.问题在于,乍一看,Parse JS API仅自动执行了增量操作,而没有执行后续的读取操作,因为增量不会返回带有在 THAT 增量期间设置的值的承诺.

Now there is a very simple operation - users ask for a unique code. The cloud function increments the current value of the index and returns the value of the array at the new index. The problem is that at first glance the Parse JS API has only increment operation performed atomically, but not the following read operation, since increment doesn't return a promise with a value which was set during THAT increment.

现在想象以下情况(伪代码):

Now imagine the following scenario (pseudocode):

字段index的值为76,两个用户尝试同时获取下一个代码:

Field index has value 76, two users try to get the next code at the same time:

User1-> increment('index') -> save -> then(obj1) -> return array[obj1.index]

User2-> increment('index') -> save -> then(obj2) -> return array[obj2.index]

现在原子增量将确保在这2次调用之后,索引列的值将为78.但是obj1obj2呢?如果它们的值读取不是与增量操作一起原子地完成的,而是在执行增量后通过获取完成的,那么它们两个都可能具有值78!并且整个唯一性逻辑将被破坏.

Now atomic increment will guarantee that after these 2 calls the index column will have value 78. But what about obj1 and obj2? If their value reading was not done atomically together with the increment operation, but was done through fetching after the increment was performed, then they both might have value 78! And the whole uniqueness logic will be broken.

有没有办法在Parse中获得原子写操作的结果?

Is there a way to get the atomic write operation result in Parse?

推荐答案

增量确实返回原子增量的最终值:

Increment does return the final value that was atomically incremented:

  1. 首先进行单元测试以显示其用法:

  1. First the unit test to show how it is used:

fit('increment', (done) => {
    new Parse.Object('Counter')
      .set('value', 1)
      .save()
      .then(result => {
        console.log('just saved', JSON.stringify(result));
        return result
          .increment('value')
          .save();
      })
      .then(result => {
        console.log('incremented', JSON.stringify(result))
        expect(result.get('value')).toBe(2);
        done();
      })
      .catch(done.fail);
  });

  • 在幕后,这是发生的事情(如果您使用mongo,则postgress也是如此):

  • Behind the scenes, here's what's happening (if you're using mongo, there's similar for postgress too):

    • MongoAdapter turns into a mongo $inc operation which is returned
    • Mongo documentation explaining $inc which includes "$inc is an atomic operation within a single document."

    这篇关于解析服务器原子增量结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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