Skip to content
kriskowal edited this page Mar 29, 2012 · 6 revisions

Reference

promise.then(fulfilled_opt, rejected_opt) — Q.when(value, fulfilled_opt, rejected_opt)

Arranges for fulfilled to be called:

  • with the value as its sole argument
  • in a future turn of the event loop
  • if and when the value is or becomes a fully resolved

Arranges for rejected to be called:

  • with a value respresenting the reason why the object will never be resolved, typically an Error object.
  • in a future turn of the event loop
  • if the value is a promise and
    • if and when the promise is rejected

Returns a promise:

  • that will resolve to the value returned by either of the callbacks, if either of those functions are called, or
  • that will be rejected if the value is rejected and no rejected callback is provided, thus forwarding rejections by default.

The value may be truly any value. It can be a function. It can be a promise.

Either callback may be falsy, in which case it will not be called.

Guarantees:

  • fulfilled will not be called before when returns.
  • rejected will not be called before when returns.
  • fulfilled will not be called more than once.
  • rejected will not be called more than once.
  • If fulfilled is called, rejected will never be called.
  • If rejected is called, fulfilled will never be called.
  • If a promise is never resolved, neither callback will ever be called.

THIS IS COOL

  • You can set up an entire chain of causes and effects in the duration of a single event and be guaranteed that any invariants in your lexical scope will not ... vary.
  • You can both receive a promise from a sketchy API and return a promise to some other sketchy API and, as long as you trust this module, all of these guarantees are still provided.
  • You can use when to compose promises in a variety of ways, for example intersection:
function and(a, b) {
    return Q.when(a, function (a) {
        return Q.when(b, function (b) {
            // ...
        });
    })
}

promise.fail(callback()) — Q.fail(promise, callback())

Accepts a promise and captures rejection with the callback, giving the callback an opportunity to recover from the failure. If the promise gets rejected, the return value of the callback resolves the returned promise. Otherwise, the fulfillment gets forwarded.

promise.fin(callback()) — Q.fin(promise, callback())

Like a finally clause, allows you to observe either the fulfillment or rejection of a callback, 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. The callback receives no arguments.

promise.end() — Q.end(value)

Accepts a promise and returns undefined, to terminate a chain of promises at the end of a program. If the promise is rejected, throws it as an exception in a future turn of the event loop.

Since exceptions thrown in when callbacks are consumed and transformed into rejections, exceptions are easy to accidentally silently ignore. It is furthermore non-trivial to get those exceptions reported since the obvious way to do this is to use when to register a rejection callback, where throw would just get consumed again. end arranges for the error to be thrown in a future turn of the event loop, so it won't be caught; it will cause the exception to emit a browser's onerror event or NodeJS's process "uncaughtException".

promise.get(name) — Q.get(object, name)

Returns a promise for the named property of an object, albeit a promise for an object.

promise.put(name, value) — Q.put(object, name, value)

Returns a promise to set the named property of an object, albeit a promise, to the given value.

promise.del(name) — Q.del(object, name)

Returns a promise to delete the named property of an object, albeit a promise.

promise.post(name, arguments) — Q.post(object, name, arguments)

Returns a promise to call the named function property of an eventually fulfilled object with the given array of arguments. The object itself is this in the function.

promise.invoke(name, ...arguments) — Q.invoke(object, name, ...arguments)

Returns a promise to call the named function property of an eventually fulfilled object with the given variadic arguments. The object itself is this in the function.

promise.keys() — Q.keys(object)

Returns a promise for an array of the property names of the eventually fulfilled object.

promiseForFunction.apply(this, arguments) — Q.apply(function, this, arguments)

Returns a promise for the result of calling an eventually fulfilled function, with the given values for the this and arguments array in that function.

promiseForFunction.call(this, ...arguments) — Q.call(function, this, ...arguments)

Returns a promise for the result of eventually calling the fulfilled function, with the given context and variadic arguments.

promiseForArrayOfPromises.all() — Q.all([...promises])

Returns a promise for an array of the fulfillment of each respective promise, or rejects when the first promise is rejected.

promiseForArray.spread(fulfilled_variadic, rejected_opt) — Q.spread(promise, fulfilled_variadic, rejected_opt)

Like then/when, but "spreads" the array into a variadic value handler. If any of the promises in the array are rejected, the rejection handler is called with the first of them. Useful especially in conjunction with all.

Q.defer()

Returns a "deferred" object with a:

  • promise property
  • resolve(value) function
  • reject(reason) function
  • node() function

The promise is suitable for passing as a value to the when function, among others.

Calling resolve with a promise notifies all observers that they must now wait for that promise to resolve.

Calling resolve with a rejected promise notifies all observers that the promise will never be fully resolved with the rejection reason. This forwards through the the chain of when calls and their returned promises until it reaches a when call that has a rejected callback.

Calling resolve with a fully resolved value notifies all observers that they may proceed with that value in a future turn. This forwards through the fulfilled chain of any pending when calls.

Calling reject with a reason is equivalent to resolving with a rejection.

In all cases where the resolution of a promise is set, (promise, rejection, value) the resolution is permanent and cannot be reset. All future observers of the resolution of the promise will be notified of the resolved value, so it is safe to call when on a promise regardless of whether it has been or will be resolved.

Calling node() returns a callback suitable for passing to a Node function.

THIS IS COOL

Deferreds 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.

  • 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. This allows a "union" abstraction like so:

function or(a, b) {
    var union = Q.defer();
    Q.when(a, union.resolve);
    Q.when(b, union.resolve);
    return union.promise;
}

Q.resolve(value)

If value is a promise, returns the promise.

If value is not a promise, returns a promise that has already been fulfilled with the given value.

Q.reject(reason)

Returns a promise that has already been rejected with the given reason.

This is useful for conditionally forwarding a rejection through an errback.

Q.when(API.getPromise(), function (value) {
    return doSomething(value);
}, function (reason) {
    if (API.stillPossible()) {
        return API.tryAgain();
    } else {
        return Q.reject(reason);
    }
})

Unconditionally forwarding a rejection is equivalent to omitting an errback on a when call. That is,

Q.when(API.getPromise(), function (value) {
    return doSomething(value);
}, function (reason) {
    return Q.reject(reason);
})

simplifies to:

Q.when(API.getPromise(), function (value) {
    return doSomething(value);
})

Q.isPromise(value)

Returns whether the given value is a promise.

promise.isResolved() — Q.isResolved(value)

Returns whether the given value is fulfilled or rejected. Non-promise values are equivalent to fulfilled promises.

promise.isFulfilled() — Q.isFulfilled(value)

Returns whether the given value is fulfilled. Non-promise values are equivalent to fulfilled promises.

promise.isRejected() — Q.isRejected(value)

Returns whether the given value is a rejected promise.

Q.async(generatorFunction)

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 examples/async-generators/README.md for further information.

Q.node(nodeFunction)

Wraps a Node function so that it returns a promise instead of accepting a callback.

var readFile = Q.node(FS.readFile);
readFile("foo.txt")
.then(function (text) {
});

The this of the call gets forwarded.

var readFile = Q.node(FS.readFile);
FS.readFile.call(FS, "foo.txt")
.then(function (text) {
});

The node call can also be used to bind and partially apply.

var readFoo = Q.node(FS.readFile, FS, "foo.txt");
readFoo()
.then(function (text) {
});

Q.ncall(nodeFunction, thisp, ...args)

Calls a Node function, returning a promise so you don’t have to pass a callback.

Q.ncall(FS.readFile, FS, "foo.txt")
.then(function (text) {
});

Q.nextTick(callback)

Calls callback in a future turn.

Advanced Reference

The resolve 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.

Q.makePromise(handlers, fallback_opt, valueOf_opt)

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.

The handlers are 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 object exists, the fallback function is called with the operator, and the subsequent variadic arguments instead. 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.

promise.send(operator, ...args) — Q.send(value, operator, ...args)

Sends an arbitrary message to a promise.

Care should be taken not to introduce control-flow hazards and security holes when forwarding messages to promises. The functions above, particularly when, 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.

Clone this wiki locally