-
Notifications
You must be signed in to change notification settings - Fork 1.2k
API Reference
Most promise methods have "static" counterparts on the main Q object, which
will accept either a promise or a non-promise, and in the latter case create
a fulfilled promise first. For example, Q.when(5, onFulfilled) is equivalent
to Q(5).then(onFulfilled). All others have static counterparts that
are named the same as the promise method.
Some methods are named the same as JavaScript reserved words, like try,
catch, and finally. This helps show the very clear parallel between standard
synchronous language constructs and asynchronous promise operations. However,
such use of words as property names is only supported as of the ECMAScript 5
edition of the JavaScript language, which isn't implemented in certain older
browsers like IE8, Safari 5, Android 2.2, or PhantomJS 1.8. If you're targeting
those browsers, and aren't using a language like CoffeeScript that takes care of
this for you, use their aliases instead, or escape them like Q["try"](...) or
promise["catch"](...).
The then method from the Promises/A+ specification, with an additional
progress handler.
Alias: promise.fail (for non-ES5 browsers)
A sugar method, equivalent to promise.then(undefined, onRejected).
A sugar method, equivalent to promise.then(undefined, undefined, onProgress).
Alias: promise.fin (for non-ES5 browsers)
Like a finally clause, allows you to observe either the fulfillment or
rejection of a promise, but to do so without modifying the final value. This is
useful for collecting resources regardless of whether a job succeeded, like
closing a database connection, shutting a server down, or deleting an unneeded
key from an object.
finally returns a promise, which will become resolved with the same
fulfillment value or rejection reason as promise. However, if callback
returns a promise, the resolution of the returned promise will be delayed until
the promise returned from callback is finished.
Much like then, but with different behavior around unhandled rejection. If
there is an unhandled rejection, either because promise is rejected and no
onRejected callback was provided, or because onFulfilled or onRejected
threw an error or returned a rejected promise, the resulting rejection reason
is thrown as an exception in a future turn of the event loop.
This method should be used to terminate chains of promises. Since exceptions
thrown in then callbacks are consumed and transformed into rejections,
exceptions are easy to accidentally, silently ignore. By arranging for the
exception to be thrown in a future turn of the event loop, so that it won't be
caught, it causes an onerror event on the browser window, or an
uncaughtException event on Node.js's process object.
Exceptions thrown by done will have long stack traces, if
Q.longStackJumpLimit is set to a positive value. If Q.onerror is set,
exceptions will be delivered there instead of thrown in a future turn.
Returns a promise to get the named property of an object. Essentially equivalent to
promise.then(function (o) {
return o[propertyName];
});Returns a promise to set the named property of an object. Essentially equivalent to
promise.then(function (o) {
o[propertyName] = value;
});Alias: promise.del (for non-ES5 browsers)
Returns a promise to delete the named property of an object. Essentially equivalent to
promise.then(function (o) {
delete o[propertyName];
});Returns a promise for the result of calling the named method of an object with
the given array of arguments. The object itself is this in the function, just
like a synchronous method call. Essentially equivalent to
promise.then(function (o) {
return o[methodName].apply(o, args);
});Alias: promise.send
Returns a promise for the result of calling the named method of an object with
the given variadic arguments. The object itself is this in the function, just
like a synchronous method call.
Returns a promise for an array of the property names of an object. Essentially equivalent to
promise.then(function (o) {
return Object.keys(o);
});Returns a new function that calls a function asynchronously with the given variadic arguments, and returns a promise. Notably, any synchronous return values or thrown exceptions are transformed, respectively, into fulfillment values or rejection reasons for the promise returned by this new function.
This method is especially useful in its static form for wrapping functions to ensure that they are always asynchronous, and that any thrown exceptions (intentional or accidental) are appropriately transformed into a returned rejected promise. For example:
var getUserData = Q.fbind(function (userName) {
if (!userName) {
throw new Error("userName must be truthy!");
}
if (localCache.has(userName)) {
return localCache.get(userName);
}
return getUserFromCloud(userName);
});Returns a promise for the result of calling a function, with the given array of arguments. Essentially equivalent to
promise.then(function (f) {
return f.apply(undefined, args);
});Note that this will result in the same return value/thrown exception translation
as explained above for fbind.
Static Alias: Q.try (ES5 browsers only)
Returns a promise for the result of calling a function, with the given variadic
arguments. Has the same return value/thrown exception translation as explained
above for fbind.
In its static form, it is aliased as Q.try, since it has semantics similar to
a try block (but handling both synchronous exceptions and asynchronous
rejections). This allows code like
Q
.try(function () {
if (!isConnectedToCloud()) {
throw new Error("The cloud is down!");
}
return syncToCloud();
})
.catch(function (error) {
console.error("Couldn't sync to the cloud", error);
});Returns a promise that is fulfilled with an array containing the fulfillment value of each promise, or is rejected with the same rejection reason as the first promise to be rejected.
This method is often used in its static form on arrays of promises, in order to execute a number of operations concurrently and be notified when they all succeed. For example:
Q.all([saveToDisk(), saveToCloud()]).done(function () {
console.log("Data saved!");
});Returns a promise that is fulfilled with an array containing the same promises as in the original array, but only after all the original promises have been resolved.
This method is often used in its static form on arrays of promises, in order to executed a number of operations concurrently and be notified when they all finish, regardless of success or failure. For example:
Q.allResolved([saveToDisk(), saveToCloud()]).spread(function (disk, cloud) {
console.log("saved to disk:", disk.isFulfilled());
console.log("saved to cloud:", cloud.isFulfilled());
}).done();It can further be combined with the state-inspection methods to see what the fulfillment value or rejection reason of each promise was.
Like then, but "spreads" the array into a variadic fulfillment handler. If any
of the promises in the array are rejected, instead calls onRejected with the
first rejected promise's rejection reason.
This is especially useful in conjunction with all, for example:
Q.all([getFromDisk(), getFromCloud()]).spread(function (diskVal, cloudVal) {
assert(diskVal === cloudVal);
}).done();Returns a promise that will have the same result as promise, except that if
promise is not fulfilled or rejected before ms milliseconds, the returned
promise will be rejected with an Error saying that the operation timed out.
Returns a promise that will have the same result as promise, but will only be
fulfilled or rejected after at least ms milliseconds have passed.
If the static version of Q.delay is passed only a single argument, it returns
a promise that will be fulfilled with undefined after at least ms
milliseconds have passed. (If it's called with two arguments, it uses the usual
static-counterpart translation, i.e. Q.delay(value, ms) is equivalent to
Q(value).delay(ms).)
This is a convenient way to insert a delay into a promise chain, or even simply
to get a nicer syntax for setTimeout:
Q.delay(150).then(doSomething);Returns whether a given promise is in the fulfilled state. When the static
version is used on non-promises, the result is always true.
Returns whether a given promise is in the rejected state. When the static
version is used on non-promises, the result is always false.
Returns whether a given promise is in the pending state. When the static version
is used on non-promises, the result is always false.
If the promise is in the fulfilled state, returns the promise's fulfillment value. If the promise is pending and waiting on another promise to complete, returns that promise. If the promise is pending and not waiting on another promise, or is rejected, simply returns the promise back.
If the promise is rejected, this property will be present (i.e. "exception" in promise.valueOf() will be true) and contain the rejection reason.
Returns a "deferred" object with a:
-
promiseproperty -
resolve(value)method -
reject(reason)method -
notify(value)method -
makeNodeResolver()method
The resolve and reject methods control the state of the promise property,
which you can hand out to others while keeping the authority to modify its state
to yourself. The notify method is for progress notification, and the
makeNodeResolver method is for interfacing with Node.js (see below).
In all cases where a promise is resolved (i.e. either fulfilled or rejected),
the resolution is permanent and cannot be reset. Attempting to call resolve,
reject, or notify if promise is already resolved will be a no-op.
Deferreds are cool because they separate the promise part from the resolver part. So:
-
You can give the promise to any number of consumers and all of them will observe the resolution independently. Because the capability of observing a promise is separated from the capability of resolving the promise, none of the recipients of the promise have the ability to "trick" other recipients with misinformation (or indeed interfere with them in any way).
-
You can give the resolver to any number of producers and whoever resolves the promise first wins. Furthermore, none of the producers can observe that they lost unless you give them the promise part too.
Calling resolve with a pending promise causes promise to wait on the passed
promise, becoming fulfilled with its fulfillment value or rejected with its
rejection reason (or staying pending forever, if the passed promise does).
Calling resolve with a rejected promise causes promise to be rejected with
the passed promise's rejection reason.
Calling resolve with a fulfilled promise causes promise to be fulfilled with
the passed promise's fulfillment value.
Calling resolve with a non-promise value causes promise to be fulfilled with
that value.
Calling reject with a reason causes promise to be rejected with that reason.
Calling notify with a value causes promise to be notified of
progress with that value. That is, any onProgress handlers registered with
promise or promises derived from promise will be called with the progress
value.
If value is a Q promise, returns the promise.
If value is a promise from another library it is coerced into a Q promise (where possible).
If value is not a promise, returns a promise that is fulfilled with value.
Returns a promise that is rejected with reason.
Synchronously calls factory(resolve, reject, notify) and returns a promise
whose state is controlled by the functions passed to factory. This is an
alternative promise-creation API that has the same power as the deferred
concept, but without introducing another conceptual entity.
If factory throws an exception, the returned promise will be rejected with
that thrown exception as the rejection reason.
Q provides a number of functions for interfacing with Node.js style
(err, result) callback APIs.
Several of these are usually used in their static form, and thus listed here as such. Nevertheless, they also exist on each Q promise, in case you somehow have a promise for a Node.js-style function or for an object with Node.js-style methods.
Note that if a Node.js-style API calls back with more than one non-error
parameter (e.g. child_process.execFile), Q packages these into an
array as the promise's fulfillment value when doing the translation.
Creates a promise-returning function from a Node.js-style function, optionally binding it with the given variadic arguments. An example:
var readFile = Q.nfbind(FS.readFile);
readFile("foo.txt", "utf-8").done(function (text) {
});Calls a Node.js-style function with the given array of arguments, returning a promise that is fulfilled if the Node.js function calls back with a result, or rejected if it calls back with an error (or throws one synchronously). An example:
Q.nfapply(FS.readFile, ["foo.txt", "utf-8"]).done(function (text) {
});Calls a Node.js-style function with the given variadic arguments, returning a promise that is fulfilled if the Node.js function calls back with a result, or rejected if it calls back with an error (or throws one synchronously). An example:
Q.nfcall(FS.readFile, "foo.txt", "utf-8").done(function (text) {
});Calls a Node.js-style method with the given arguments array, returning a promise that is fulfilled if the method calls back with a result, or rejected if it calls back with an error (or throws one synchronously). An example:
Q.npost(redisClient, ["get", "user:1:id"]).done(function (user) {
});Alias: Q.nsend
Calls a Node.js-style method with the given variadic arguments, returning a promise that is fulfilled if the method calls back with a result, or rejected if it calls back with an error (or throws one synchronously). An example:
Q.npost(redisClient, "get", "user:1:id").done(function (user) {
});If callback is a function, assumes it's a Node.js-style callback, and calls it
as either callback(rejectionReason) when/if promise becomes rejected, or
as callback(null, fulfillmentValue) when/if promise becomes fulfilled. If
callback is not a function, simply returns promise.
This method is useful for creating dual promise/callback APIs, i.e. APIs that return promises but also accept Node.js-style callbacks. For example:
function createUser(userName, userData, callback) {
return database.ensureUserNameNotTaken(userName)
.then(function () {
database.saveUserData(userName, userData);
})
.nodeify(callback);
}Returns a function suitable for passing to a Node.js API. That is, it has a
signature (err, result) and will reject promise with err if err is
given, or fulfill it with result if that is given.
Returns whether the given value is a Q promise.
This is an experimental tool for converting a generator function into a deferred
function. This has the potential of reducing nested callbacks in engines that
support yield. See the generators example for further information.
Calls callback in a future turn of the event loop.
A settable property that will intercept any uncaught errors that would otherwise
be thrown in the next tick of the event loop, usually as a result of done.
Can be useful for getting the full stack trace of an error in browsers, which is
not usually possible with window.onerror.
A settable property that lets you specify how many "stack jumps" should be
tracked in asynchronous operations, so that if an uncaught error is thrown by
done or a rejection reason's stack property is inspected in a rejection
callback, a long stack trace is produced.
As of this writing, the default value is 1, and setting it higher does not
work yet. If you are using Q in performance- or memory-sensitive situations, it
should be set to 0.
The Q promise constructor establishes the basic API for performing operations
on objects: "get", "put", "del", "post", "apply", and "keys". This set of
"operators" can be extended by creating promises that respond to messages with
other operator names, and by sending corresponding messages to those promises.
Creates a stand-alone promise that responds to messages. These messages have an operator like "when", "get", "put", and "post", corresponding to each of the above functions for sending messages to promises.
handlers is an object with function properties corresponding to operators.
When the made promise receives a message and a corresponding operator exists in
the handlers, the function gets called with the variadic arguments sent to the
promise. If no handlers entry exists for that message, the fallback
function is called with the operator and the subsequent variadic arguments.
These functions return a promise for the eventual resolution of the promise
returned by the message-sender. The default fallback returns a rejection.
The valueOf function, if provided, overrides the valueOf function of the
returned promise. This is useful for providing information about the promise in
the same turn of the event loop. For example, resolved promises return their
resolution value and rejections return an object that is recognized by
isRejected.
Sends an arbitrary message to a promise, with the given array of arguments.
Care should be taken not to introduce control-flow hazards and security holes
when forwarding messages to promises. The functions above, particularly then,
are carefully crafted to prevent a poorly crafted or malicious promise from
breaking the invariants like not applying callbacks multiple times or in the
same turn of the event loop.