dojo/_base/Deferred

Summary

Deprecated. This module defines the legacy dojo/_base/Deferred API. New code should use dojo/Deferred instead.

The Deferred API is based on the concept of promises that provide a generic interface into the eventual completion of an asynchronous action. The motivation for promises fundamentally is about creating a separation of concerns that allows one to achieve the same type of call patterns and logical data flow in asynchronous code as can be achieved in synchronous code. Promises allows one to be able to call a function purely with arguments needed for execution, without conflating the call with concerns of whether it is sync or async. One shouldn't need to alter a call's arguments if the implementation switches from sync to async (or vice versa). By having async functions return promises, the concerns of making the call are separated from the concerns of asynchronous interaction (which are handled by the promise).

The Deferred is a type of promise that provides methods for fulfilling the promise with a successful result or an error. The most important method for working with Dojo's promises is the then() method, which follows the CommonJS proposed promise API. An example of using a Dojo promise:

var resultingPromise = someAsyncOperation.then(function(result){
    ... handle result ...
},
function(error){
    ... handle error ...
});

The .then() call returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.

The Deferred instances also provide the following functions for backwards compatibility:

  • addCallback(handler)
  • addErrback(handler)
  • callback(result)
  • errback(result)

Callbacks are allowed to return promises themselves, so you can build complicated sequences of events with ease.

The creator of the Deferred may specify a canceller. The canceller is a function that will be called if Deferred.cancel is called before the Deferred fires. You can use this to implement clean aborting of an XMLHttpRequest, etc. Note that cancel will fire the deferred with a CancelledError (unless your canceller returns another kind of error), so the errbacks should be prepared to handle that error for cancellable Deferreds.

Usage

Deferred(canceller);
Parameter Type Description
canceller Function
Optional

See the dojo/_base/Deferred reference documentation for more information.

Examples

Example 1

var deferred = new Deferred();
setTimeout(function(){ deferred.callback({success: true}); }, 1000);
return deferred;

Example 2

Deferred objects are often used when making code asynchronous. It may be easiest to write functions in a synchronous manner and then split code using a deferred to trigger a response to a long-lived operation. For example, instead of register a callback function to denote when a rendering operation completes, the function can simply return a deferred:

// callback style:
function renderLotsOfData(data, callback){
    var success = false
    try{
        for(var x in data){
            renderDataitem(data[x]);
        }
        success = true;
    }catch(e){ }
    if(callback){
        callback(success);
    }
}


// using callback style
renderLotsOfData(someDataObj, function(success){
    // handles success or failure
    if(!success){
        promptUserToRecover();
    }
});
// NOTE: no way to add another callback here!!

Example 3

Using a Deferred doesn't simplify the sending code any, but it provides a standard interface for callers and senders alike, providing both with a simple way to service multiple callbacks for an operation and freeing both sides from worrying about details such as "did this get called already?". With Deferreds, new callbacks can be added at any time.

// Deferred style:
function renderLotsOfData(data){
    var d = new Deferred();
    try{
        for(var x in data){
            renderDataitem(data[x]);
        }
        d.callback(true);
    }catch(e){
        d.errback(new Error("rendering failed"));
    }
    return d;
}


// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
    promptUserToRecover();
});
// NOTE: addErrback and addCallback both return the Deferred
// again, so we could chain adding callbacks or save the
// deferred for later should we need to be notified again.

Example 4

In this example, renderLotsOfData is synchronous and so both versions are pretty artificial. Putting the data display on a timeout helps show why Deferreds rock:

// Deferred style and async func
function renderLotsOfData(data){
    var d = new Deferred();
    setTimeout(function(){
        try{
            for(var x in data){
                renderDataitem(data[x]);
            }
            d.callback(true);
        }catch(e){
            d.errback(new Error("rendering failed"));
        }
    }, 100);
    return d;
}


// using Deferred style
renderLotsOfData(someDataObj).then(null, function(){
    promptUserToRecover();
});

Note that the caller doesn't have to change his code at all to handle the asynchronous case.

Properties

fired

Defined by: dojo/_base/Deferred

promise

Defined by: dojo/_base/Deferred

Methods

addBoth(callback)

Defined by dojo/_base/Deferred

Add handler as both successful callback and error callback for this deferred instance.

Parameter Type Description
callback Function

Returns: any | undefined

Returns this deferred object.

addCallback(callback)

Defined by dojo/_base/Deferred

Adds successful callback for this deferred instance.

Parameter Type Description
callback Function

Returns: any | undefined

Returns this deferred object.

addCallbacks(callback,errback)

Defined by dojo/_base/Deferred

Adds callback and error callback for this deferred instance.

Parameter Type Description
callback Function
Optional

The callback attached to this deferred object.

errback Function
Optional

The error callback attached to this deferred object.

Returns: any

Returns this deferred object.

addErrback(errback)

Defined by dojo/_base/Deferred

Adds error callback for this deferred instance.

Parameter Type Description
errback Function

Returns: any | undefined

Returns this deferred object.

callback(value)

Defined by dojo/_base/Deferred

Fulfills the Deferred instance successfully with the provide value

Parameter Type Description
value undefined

cancel()

Defined by dojo/_base/Deferred

Cancels the asynchronous operation

errback(error)

Defined by dojo/_base/Deferred

Fulfills the Deferred instance as an error with the provided error

Parameter Type Description
error undefined

isCanceled()

Defined by dojo/_base/Deferred

Checks whether the deferred has been canceled.

Returns: Boolean

isFulfilled()

Defined by dojo/_base/Deferred

Checks whether the deferred has been resolved or rejected.

Returns: Boolean

isRejected()

Defined by dojo/_base/Deferred

Checks whether the deferred has been rejected.

Returns: Boolean

isResolved()

Defined by dojo/_base/Deferred

Checks whether the deferred has been resolved.

Returns: Boolean

progress(update)

Defined by dojo/_base/Deferred

Send progress events to all listeners

Parameter Type Description
update undefined

reject(error)

Defined by dojo/_base/Deferred

Fulfills the Deferred instance as an error with the provided error

Parameter Type Description
error undefined

resolve(value)

Defined by dojo/_base/Deferred

Fulfills the Deferred instance successfully with the provide value

Parameter Type Description
value undefined

then(resolvedCallback,errorCallback,progressCallback)

Defined by dojo/_base/Deferred

Adds a fulfilledHandler, errorHandler, and progressHandler to be called for completion of a promise. The fulfilledHandler is called when the promise is fulfilled. The errorHandler is called when a promise fails. The progressHandler is called for progress events. All arguments are optional and non-function values are ignored. The progressHandler is not only an optional argument, but progress events are purely optional. Promise providers are not required to ever create progress events.

This function will return a new promise that is fulfilled when the given fulfilledHandler or errorHandler callback is finished. This allows promise operations to be chained together. The value returned from the callback handler is the fulfillment value for the returned promise. If the callback throws an error, the returned promise will be moved to failed state.

Parameter Type Description
resolvedCallback Function
Optional
errorCallback Function
Optional
progressCallback Function
Optional

Returns: any

Returns a new promise that represents the result of the execution of the callback. The callbacks will never affect the original promises value.

Examples

Example 1

An example of using a CommonJS compliant promise:

asyncComputeTheAnswerToEverything().
    then(addTwo).
    then(printResult, onError);
>44

when(valueOrPromise,callback,errback,progback)

Defined by dojo/when

Transparently applies callbacks to values and/or promises.

Accepts promises but also transparently handles non-promises. If no callbacks are provided returns a promise, regardless of the initial value. Foreign promises are converted.

If callbacks are provided and the initial value is not a promise, the callback is executed immediately with no error handling. Returns a promise if the initial value is a promise, or the result of the callback otherwise.

Parameter Type Description
valueOrPromise undefined

Either a regular value or an object with a then() method that follows the Promises/A specification.

callback Function
Optional

Callback to be invoked when the promise is resolved, or a non-promise is received.

errback Function
Optional

Callback to be invoked when the promise is rejected.

progback Function
Optional

Callback to be invoked when the promise emits a progress update.

Returns: dojo/promise/Promise | summary: | name:

Promise, or if a callback is provided, the result of the callback.

© 2005–2017 JS Foundation
Licensed under the AFL 2.1 and BSD 3-Clause licenses.
http://dojotoolkit.org/api/1.10/dojo/_base/Deferred.html