避免在Realm.open中对nodejs / react-native进行回调地狱

时间:2018-03-30 05:48:45

标签: javascript node.js reactjs react-native realm

Realm's getting started查看此示例。如果你需要做更复杂的写作,它会受到回归地狱的影响而变得更糟。

Realm.open({schema: [CarSchema, PersonSchema]})
  .then(realm => {
    // Create Realm objects and write to local storage
    realm.write(() => {
      const myCar = realm.create('Car', {
        make: 'Honda',
        model: 'Civic',
        miles: 1000,
      });
      myCar.miles += 20; // Update a property value
    });

    // Query Realm for all cars with a high mileage
    const cars = realm.objects('Car').filtered('miles > 1000');

    // Will return a Results object with our 1 car
    cars.length // => 1

    // Add another car
    realm.write(() => {
      const myCar = realm.create('Car', {
        make: 'Ford',
        model: 'Focus',
        miles: 2000,
      });
    });

    // Query results are updated in realtime
    cars.length // => 2
  })
  .catch(error => {
    console.log(error);
  });

避免滥用回调的一个好方法是使用命名函数而不是匿名函数。

这是我带来的:

     writeMsgs  = () => {
        record = message => {
            id = md5('random thing...')
            doc =  {id             : id                   ,
                    favorite       : message.favorite     ,
                    }
            realm.create(tableName, doc)
        }
        SomethingThatReturnsPromise.then(messages => messages.map(record))
        this.setState( { loading: false, refreshing: false } )
    }
    realmWrite = realm           => realm.write(writeMsgs)
    realmOpen  = ()              => Realm.open(schemas).then(realmWrite)

然后我只需要realmOpen()来触发realmWrite。问题是:realm.write采用不带参数的回调作为其参数。但在此回调中,使用realm对象。只有在匿名传递回调时才可以执行此操作。如果我给它一个名字,它就不可能。

我执行了以下操作以在范围中包含realm

     writeMsgs  = realm => () => {
        record = message => {
            id = md5('random thing...')
            doc =  {id             : id                   ,
                    favorite       : message.favorite     ,
                    }
            realm.create(tableName, doc)
        }
        SomethingThatReturnsPromise.then(messages => messages.map(record))
        this.setState( { loading: false, refreshing: false } )
    }
    realmWrite = realm           => realm.write(writeMsgs(realm))
    realmOpen  = ()              => Realm.open(schemas).then(realmWrite)

但是,Realm遵守:无法修改写入事务的托管对象

我不知道写入事务机制是如何工作的,但看起来它不能适应以避免过度使用回调。对我来说realm.write(anonymous_function_here_that_actually_writes_things)毫无意义。为什么不只是real.write(document_to_write)

1 个答案:

答案 0 :(得分:1)

你可以在一个promise函数中包含realm write write,所以一切都可以链接和线性

const realmWrite(name,obj)=>    
  new Promise((resolve,reject)=>
    realm.write(() => {
      return resolve(realm.create(name,obj))
   })
})


...then(()=>realmWrite('car',{
    make: 'Ford',
    model: 'Focus',
    miles: 2000,
  })) 
.then(car=>{})