ShowTable of Contents
This article provides examples of how to use the Mashup Center JavaScript API with deferred objects.
Certain operations of the JavaScript Enabler API involve handling HTTP requests. Deferred objects allow to synchronously and asynchronously handle such operations. For such handling, deferred objects allow to define callbacks, which are invoked at specific points in time of such operations. For example, a foreachCallback allows to invoke a callback for each iteration of an iterator, or a finishedCallback allows to invoke a callback after the whole operation finished.
Working with deferred objects
Deferred objects are returned by certain methods of the Enabler API, for example by getRoot() of the navigation model. Deferred objects need to be used to define one or more callbacks and afterwards, to start the operation itself. When you start the operation, you specify whether you want to start it synchronously or asynchronously. In case the operation is started synchronously, the JavaScript processing continues only after the operation finishes, in case it is started asynchronously, it proceeds immediately. Note that the callbacks are invoked in both cases to provide results. When a callback is invoked, a result, a status, and a parameter object is passed to the callback.
Example 1: Using a deferred object to obtain the root node of the navigation model
// using the deferred object
var dfr = nm.getRoot();
var parameters = {name: "hugo"};
dfr.setFinishedCallback(getRoot_finished, parameters);
dfr.start();
// callback function
function getRoot_finished(result, status, parameters) {
// handle result with regards to status
if (status == 400) {
var root = result;
...
}
// may use parameter object
if (parameters) {
alert(parameters.name); // alert("hugo");
...
}
}
Example 2: Starting an operation synchronously (by using the default of the start method)
// using the deferred object
var dfr = nm.getRoot();
dfr.setFinishedCallback(getRoot_finished);
dfr.start(); // respectively dfr.start(true); to explicitly specify the mode to start
// subsequent code is processed only after the
// above operation is finished
Example 3: Starting an operation asynchronously
// using the deferred object
var dfr = nm.getRoot();
dfr.setFinishedCallback(getRoot_finished);
dfr.start(false);
// subsequent code is processed immediately