back to Overview

_.promise()

Creates a new Promise, optionally assimilating other promises.
Complete distribution only, not available in stand-alone modules.

Syntax Variants

_.promise()
_.promise(otherPromises...)

Parameters

otherPromises
one or more promises to assimilate (varargs). You can also pass lists of promises.
(return value)
the new promise.

Description

Creates a new Promise, optionally assimilating other promises. If no other promise is given, a fresh new promise is returned.

The returned promise provides the methods fulfill() and reject() that can be called directly to change the promise's state, as well as the more powerful fire().

If one promise is given as parameter, the new promise assimilates the given promise as-is, and just forwards fulfillment and rejection with the original values.

If more than one promise are given, it will assimilate all of them with slightly different rules:

  • the new promise is fulfilled if all assimilated promises have been fulfilled. The fulfillment values of all assimilated promises are given to the handler as arguments. Note that the fulfillment values themselves are always arrays, as a promise can have several fulfillment values in Minified's implementation.
  • when one of the promises is rejected, the new promise is rejected immediately. The rejection handler gets the promises rejection value (first argument if it got several) as first argument, an array of the result values of all promises as a second (that means one array of arguments for each promise), and the index of the failed promise as third.

Example

A simple promise that is fulfilled after 1 second, using Minified's invocation syntax:

var p = _.promise();
setTimeout(function() {
    p.fire(true);
}, 1000);

Example

Request three files in parallel. When all three have been downloaded, concatenate them into a single string.

var files = _('fileA.txt', 'fileA.txt', 'fileC.txt');
var content;
_.promise(files.map(function(file) {
     return $.request('get', '/txts/' + file);
})).then(function(fileRslt1, fileRslt2, fileRslt3) {
     content = _(fileRslt1, fileRslt2, fileRslt3).map( function(result) { return result[0]; }).join('');
}).error(function(status, response, xhr, url) {
   alert('failed to load file '+url);
});

Comments

comments powered by Disqus

back to Overview

Functions