我在我的项目中使用以下代码来异步打开 Realm 并将其与服务一起使用。
RmProfile.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;
现在要在其他文件中使用 Realm 服务,我只是尝试导出
Profile.js:
import PrflSrvcs from './ProfileServices'
console.log(PrflSrvcs.getName('1253'));
这里服务正在导出,但出现错误,例如 RmPrfl 未定义。这是因为 Realm.Open() 是异步执行的,并且在其执行结束之前,ProfileServices 被执行。
由于我是 Realm 的新手,任何人都可以指导我如何使用 Realm JavaScript 进行异步事务。
任何例子都会很好理解。
谢谢你..
最佳答案
你为什么不把这一切都包裹在一个 promise 中,例如
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) });
您可能不想为每个查询打开 Realm ,您可以缓存它并在运行打开之前检查是否存在。
关于javascript - 如何异步打开 Realm(JavaScript) 对象并将其与服务一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48756313/