如何异步打开Realm(JavaScript)对象并将其与服务一起使用

时间:2018-02-12 22:07:18

标签: javascript realm

我在我的项目中使用下面的代码来异步打开领域并将其与服务一起使用。

RmProfile.js:

attr

现在在其他文件中使用领域服务我只是想导出

Profile.js:

import Realm from 'realm';
const PrflSchema = {
  name: 'Profile',
  primaryKey: 'id',
  properties: {
    id            : {type: 'int'},
    mob            : {type: 'int'},
    name        : {type: 'string'},
  }
};

let RmPrfl;

Realm.open({
      schema: [PrflSchema],
      schemaVersion: 0
    }).then(realm => {
        RmPrfl = realm;
    })
    .catch(error => {
        console.log('Error in Opening PrflSchema');
        console.log(error);
      });

let ProfileServices= {
    getName: function(id) {
        let PrflInfo=RmPrfl.objectForPrimaryKey('Profile', id);
        if(PrflInfo){
            return PrflInfo.name;
        }
        else{
            return false;
        }
    }
}
module.exports = ProfileServices;

此处导出的服务但错误就像RmPrfl未定义一样。这是因为Realm.Open()是异步执行的,并且在执行结束之前,执行了ProfileServices。

因为我是Realm的新手,任何人都可以指导我,如何使用Realm JavaScript进行异步交易。

任何一个例子都很好理解。

谢谢..

2 个答案:

答案 0 :(得分:1)

你为什么不把它们全部包装在一个诺言中呢?

let ProfileServices = () => {
    getName: function(id) {
      return new Promise((resolve, reject) => {
        Realm.open({
              schema: [PrflSchema],
              schemaVersion: 0
          })
          .then(realm => {
              let PrflInfo = realm.objectForPrimaryKey('Profile', id);
              resolve(PrflInfo || false)
          })
          .catch(error => {
              console.log('Error in Opening PrflSchema');
              console.log(error);
              reject(error)
          });
      })
    }
}

module.exports = ProfileServices

import PrflSrvcs from './ProfileServices'
PrflSrvcs.getName('1253')
  .then(name => { console.log(name) });

尽管您可能不想打开每个查询的领域,但可以在运行打开之前将其缓存并检查是否存在。

答案 1 :(得分:0)

文档中不清楚,但似乎Realm.open(config)缓存了承诺的领域本身,因此您实际上可以对每个查询使用该API。

# Initial Ream.open():  took 176.50000000139698 milliseconds.
# Manually Cached:      took 0.5999999993946403 milliseconds.
# Second Realm.open():  took 0.19999999494757503 milliseconds.

因此,手动缓存只会增加一些额外的开销,而不会简化用于访问领域的API。

这是我使用的缓存功能:

    private realm(): Promise<Realm> {
      return new Promise((resolve, reject) => {
        if (this.cachedRealm) {
          resolve(this.cachedRealm)
        } else {
          Realm.open(this.config)
            .then(realm => {
              this.cachedRealm = realm
              resolve(realm)
            })
            .catch(error => {
                console.error(error);
                reject(error)
            });
        }
      })
    }
相关问题