Realm JavaScript Async APIs.
Because Realm-JS primarily runs in the Node environment, we should respect Node's event driven model. Realm is extremely fast but since it sees frequent use in the server we have to be very conscientious about not blocking the native event loop.
While for almost all operations to Realm can be done synchronously we also need async apis that allow the application to continue.
Examples that Block the Event Loop 😓
realm.write(() => {
for(var i = 0; i++; i < 100000){
realm.create('Item', {
_id: i
})
}
})
console.log('done')
In the following example, you'll notice that "done" doesn't get printed out until a long while after. This means that the main process is being held up with each event write.
Alleviating the Issue 😋
The new Realm-JS APIs allow users to loop both a traditional callback as well as a promise.
realm.createAsync('Item', {_id: i}, (err, item) {
if(err) { console.error(err) }
})
If no callback is supplied to createAsync
then a Promise<Realm.Object>
is returned.
realm.createAsync('Item', {_id: i})
.then(item => {
console.log(item)
})
.catch(console.error)
This makes it great to use it with async
and await
APIs in the new ECMAScript 7 or TypeScript spec.
for(var i = 0; i++; i < 10000) {
await realm.createAsync('Item', {_id: i})
}
console.log('done')
With the example above we have the application printing "done" but the entire application is not held up. It can continue to process other events.