Learn about JSONStore concurrency.
Most of the operations that can be performed on a collection, such as add and find, are asynchronous. These operations return a jQuery promise that is resolved when the operation completes successfully and rejected when a failure occurs. These promises are similar to success and failure callbacks.
A jQuery Deferred is a promise that can be resolved or rejected. The following examples are not specific to JSONStore, but are intended to help you understand their usage in general.
The Options Object with onSuccess and onFailure callbacks that were used in JSONStore for IBM® Worklight® V5.0.5 are deprecated in favor of promises.
Instead of promises and callbacks, you can also listen to JSONStore success ('WL/JSONSTORE/SUCCESS') and failure ('WL/JSONSTORE/FAILURE' events. Perform actions that are based on the arguments that are passed to the event listener.
var asyncOperation = function () {
// Assumes that you have jQuery defined via $ in the environment
var deferred = $.Deferred();
setTimeout(function() {
deferred.resolve('Hello');
}, 1000);
return deferred.promise();
};
// The function that is passed to .then is executed after 1000 ms.
asyncOperation.then(function (response) {
// response = 'Hello'
});
var asyncOperation = function (callback) {
setTimeout(function() {
callback('Hello');
}, 1000);
};
// The function that is passed to asyncOperation is executed after 1000 ms.
asyncOperation(function (response) {
// response = 'Hello'
});
$(document.body).on('WL/JSONSTORE/SUCCESS', function (evt, data, src, collectionName) {
// evt - Contains information about the event
// data - Data that is sent ater the operation (add, find, etc.) finished
// src - Name of the operation (add, find, push, etc.)
// collectionName - Name of the collection
});
When you use the Native iOS API for JSONStore, all operations are added to a synchronous dispatch queue. This behavior ensures that operations that touch the store are executed in order on a thread that is not the main thread. For more information, see the Apple documentation at Grand Central Dispatch (GCD).
When you use the Native Android API for JSONStore, all operations are executed on the main thread. You must create threads or use thread pools to have asynchronous behavior. All store operations are thread-safe.