如何在异步获取请求中使用领域?

时间:2018-12-17 09:15:41

标签: react-native mobile async-await realm-js

我已满足我的要求:

步骤1.将数据保存到手机(域)中的本地数据库

步骤2.将本地数据上传到服务器,如果成功,服务器将返回数据ID 第3步。通过在步骤2中获得的返回ID删除本地db中的记录

Realm.open({schema:[MySchame],encryptionKey:getRealmKey()})
        .then(realm =>{
            realm.write(() => {
                // 1. get all step data from db
                let objetcs = realm.objects('MySchema');
                // 2. upload obtained data to server
                if(objetcs.length > 0){
                    let recordArr = [];
                    for (let o of steps){
                        recordArr.push(o.get());
                    }
                   uploadDataToServer(recordArr,(res)=>{
                        //3. filter the uploaded steps and delete them
                        let uploadedSteps = realm.objects('MySchema').filtered('id=$0',res.id);
                        if(uploadedSteps.length > 0){
                            realm.delete(uploadedSteps);
                        }
                    });
                }
            });
            realm.close();
        })
        .catch(error =>{
            console.log(error);
        });

但这不能按预期工作,似乎数据库关闭比网络成功回调还早。 谢谢你的想法。

2 个答案:

答案 0 :(得分:0)

首先创建下面的服务

import repository from "./realmConfig";

let CatalogsService = {
  findAll: function() {
    return repository.objects("CatalogsModel");
  },

  save: function(catalogs) {
    repository.write(() => {
      repository.create("CatalogsModel", catalogs);
    });
  },
  delete: function() {
    repository.write(() => {
      let all = repository.objects("CatalogsModel");
      repository.delete(all);
    });
  },

  update: function(catalogs, callback) {
    if (!callback) return;
    repository.write(() => {
      callback();
      catalogs.updatedAt = new Date();
    });
  }
};

module.exports = CatalogsService;

我的realmConfig文件所在的位置

 import Realm from "realm";

class CatalogsModel extends Realm.Object {}
CatalogsModel.schema = {
  name: "CatalogsModel",
  primaryKey: "id",
  properties: {
    id: "string",
    name: "string",
    url: "string",
    status: "int"
  }
};
class OffersModel extends Realm.Object {}
OffersModel.schema = {
  name: "OffersModel",
  primaryKey: "id",
  properties: {
    id: "string",
    name: "string",
    url: "string",
    status: "int",
    machineId: "string",
    machineName: "string"
  }
};

export default new Realm({
schema: [CatalogsModel, OffersModel],
schemaVersion: 1,
deleteRealmIfMigrationNeeded: true

 });

现在将Service.js导入到您要调用async服务器调用的位置并完成您的工作。供参考,请参见下面的代码

import CatalogService from './path/to/CatalogService .js'

//get objects
var catalogs = CatalogsService.findAll();

// fire async function , I prefer axios for network calls

 Axios.post("SERVER_URL", {
      data: catalogs
    })
    .then(function(response) {
      if(response.success)        
       CatalogsService.delete()
}

我认为您可以根据需要轻松修改findAll()delete()方法

答案 1 :(得分:0)

最后,我使用这样的领域:

let realm = new Realm({schema:[JOB_SCHEMA.jobTrack],encryptionKey:getRealmKey()});
        let objects = realm.objects('JobTrack');
        realm.beginTransaction();
        realm.delete(objects);
        realm.commitTransaction();
        realm.close();