如何阻止Realmjs中的多个beginTransactions?

时间:2019-01-18 07:14:30

标签: react-native realm-js

我创建了一个处理交易的函数,然后将其调用到多个地方。当我打开新事务时另一个事务尚未完成时,我崩溃了。

这是我的代码:

const RealmMakeTransaction = async (action) => {
    try {
        realm.GetInstance().beginTransaction();
        let response = await action();
        realm.GetInstance().commitTransaction();

        return response;

    } catch (e) {

        realm.GetInstance().cancelTransaction();
    }
};

1 个答案:

答案 0 :(得分:0)

在致电realm之前,您可以通过致电beginTransaction()来轻松检查realm.GetInstance().isInTransaction是否已经在交易中

您的代码如下:

const RealmMakeTransaction = async (action) => {

   //use single instance
   let realm = realm.GetInstance();

    try {
        if( realm.isInTransaction)
          realm.cancelTransaction();

        realm.beginTransaction();
        let response = await action();
        realm.commitTransaction();
        return response;

    } catch (e) {

        realm.cancelTransaction();
        realm.close();
    }
};