Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jan 22, 2025. It is now read-only.
/qPublic archive

API Reference

lucasprus edited this pageJan 23, 2017 ·63 revisions

Promise Methods

Most promise methods have "static" counterparts on the mainQ object, whichwill accept either a promise or a non-promise, and in the latter case createa fulfilled promise first. For example,Q.when(5, onFulfilled) is equivalenttoQ(5).then(onFulfilled). All others have static counterparts thatare named the same as the promise method.

Some methods are named the same as JavaScript reserved words, liketry,catch, andfinally. This helps show the very clear parallel between standardsynchronous language constructs and asynchronous promise operations. However,such use of words as property names is only supported as of the ECMAScript 5edition of the JavaScript language, which isn't implemented in certain olderbrowsers like IE8, Safari 5, Android 2.2, or PhantomJS 1.8. If you're targetingthose browsers, and aren't using a language like CoffeeScript that takes care ofthis for you, use their aliases instead, or escape them likeQ["try"](...) orpromise["catch"](...).

Core Promise Methods

promise.then(onFulfilled, onRejected, onProgress)

Thethen method from thePromises/A+ specification, with an additionalprogress handler.

promise.catch(onRejected)

Alias:promise.fail (for non-ES5 browsers)

A sugar method, equivalent topromise.then(undefined, onRejected).

promise.progress(onProgress)

Deprecated:promise.observeEstimate or a similar interface is due to replace this method in version 2. Progress does not compose well.https://github.com/kriskowal/gtor#progress-and-estimated-time-to-completion

A sugar method, equivalent topromise.then(undefined, undefined, onProgress).TheonProgress handler receives values that were sent to this promise either from thenotify method of the corresponding deferred, or from the promise that this promise became by virtue of being returned from a handler.

promise.finally(callback)

Alias:promise.fin (for non-ES5 browsers)

Like afinally clause, allows you to observe either the fulfillment orrejection of a promise, but to do so without modifying the final value. This isuseful for collecting resources regardless of whether a job succeeded, likeclosing a database connection, shutting a server down, or deleting an unneededkey from an object.

finally returns a promise, which will become resolved with the samefulfillment value or rejection reason aspromise. However, ifcallbackreturns a promise, the resolution of the returned promise will be delayed untilthe promise returned fromcallback is finished. Furthermore, if the returnedpromise rejects, that rejection will be passed down the chain instead of theprevious result.

promise.done(onFulfilled, onRejected, onProgress)

Much likethen, but with different behavior around unhandled rejection. Ifthere is an unhandled rejection, either becausepromise is rejected and noonRejected callback was provided, or becauseonFulfilled oronRejectedthrew an error or returned a rejected promise, the resulting rejection reasonis thrown as an exception in a future turn of the event loop.

This method should be used to terminate chains of promises that will not bepassed elsewhere. Since exceptions thrown inthen callbacks are consumed andtransformed into rejections, exceptions at the end of the chain are easy toaccidentally, silently ignore. By arranging for the exception to be thrown in afuture turn of the event loop, so that it won't be caught, it causes anonerror event on the browserwindow, or anuncaughtException event onNode.js'sprocess object.

Exceptions thrown bydone will have long stack traces, ifQ.longStackSupport is set totrue. IfQ.onerror is set,exceptions will be delivered there instead of thrown in a future turn.

The Golden Rule ofdone vs.then usage is: eitherreturn your promise tosomeone else, or if the chain ends with you, calldone to terminate it. Terminatingwithcatch is not sufficient because the catch handler may itself throw an error.

Promise-for-Object Methods

promise.get(propertyName)

Returns a promise to get the named property of an object. Essentially equivalentto

promise.then(function(o){returno[propertyName];});

promise.post(methodName, args)

Experimental Alias:promise.mapply

Returns a promise for the result of calling the named method of an object withthe given array of arguments. The object itself isthis in the function, justlike a synchronous method call. Essentially equivalent to

promise.then(function(o){returno[methodName].apply(o,args);});

promise.invoke(methodName, ...args)

Alias:promise.send

Experimental Alias:promise.mcall

Returns a promise for the result of calling the named method of an object withthe given variadic arguments. The object itself isthis in the function, justlike a synchronous method call.

promise.keys()

Returns a promise for an array of the property names of an object. Essentiallyequivalent to

promise.then(function(o){returnObject.keys(o);});

Promise-for-Function Methods

promise.fbind(...args)(deprecated)

Returns a new function that calls a function asynchronously with the givenvariadic arguments, and returns a promise. Notably, any synchronous returnvalues or thrown exceptions are transformed, respectively, into fulfillmentvalues or rejection reasons for the promise returned by this new function.

This method is especially useful in its static form for wrapping functions toensure that they are always asynchronous, and that any thrown exceptions(intentional or accidental) are appropriately transformed into a returnedrejected promise. For example:

vargetUserData=Q.fbind(function(userName){if(!userName){thrownewError("userName must be truthy!");}if(localCache.has(userName)){returnlocalCache.get(userName);}returngetUserFromCloud(userName);});

promise.fapply(args)

Returns a promise for the result of calling a function, with the given array ofarguments. Essentially equivalent to

promise.then(function(f){returnf.apply(undefined,args);});

Note that this will result in the same return value/thrown exception translationas explained above forfbind.

promise.fcall(...args)

Static Alias:Q.try (ES5 browsers only)

Returns a promise for the result of calling a function, with the given variadicarguments. Has the same return value/thrown exception translation as explainedabove forfbind.

In its static form, it is aliased asQ.try, since it has semantics similar toatry block (but handling both synchronous exceptions and asynchronousrejections). This allows code like

Q.try(function(){if(!isConnectedToCloud()){thrownewError("The cloud is down!");}returnsyncToCloud();}).catch(function(error){console.error("Couldn't sync to the cloud",error);});

Promise-for-Array Methods

promise.all()

Returns a promise that is fulfilled with an array containing the fulfillmentvalue of each promise, or is rejected with the same rejection reason as thefirst promise to be rejected.

This method is often used in its static form on arrays of promises, in order toexecute a number of operations concurrently and be notified when they allsucceed. For example:

Q.all([getFromDisk(),getFromCloud()]).done(function(values){assert(values[0]===values[1]);// values[0] is fromDisk and values[1] is fromCloud});

promise.allSettled()

Returns a promise that is fulfilled with an array of promise state snapshots,but only after all the original promises have settled, i.e. become eitherfulfilled or rejected.

This method is often used in its static form on arrays of promises, in order toexecute a number of operations concurrently and be notified when they allfinish, regardless of success or failure. For example:

Q.allSettled([saveToDisk(),saveToCloud()]).spread(function(disk,cloud){console.log("saved to disk:",disk.state==="fulfilled");console.log("saved to cloud:",cloud.state==="fulfilled");}).done();

The state snapshots will be in the same form as those retrieved viapromise.inspect, i.e. either{ state: "fulfilled", value: v } or{ state: "rejected", reason: r }.

promise.spread(onFulfilled, onRejected)

Likethen, but "spreads" the array into a variadic fulfillment handler. If anyof the promises in the array are rejected, instead callsonRejected with thefirst rejected promise's rejection reason.

This is especially useful in conjunction withall, for example:

Q.all([getFromDisk(),getFromCloud()]).spread(function(diskVal,cloudVal){assert(diskVal===cloudVal);}).done();

Utility Methods

promise.thenResolve(value)

No Static Counterpart

A sugar method, equivalent topromise.then(function () { return value; }).

promise.thenReject(reason)

No Static Counterpart

A sugar method, equivalent topromise.then(function () { throw reason; }).

promise.tap(onFulfilled)

Introduced in version 1.1.0 (November 2014)

Attaches a handler that will observe the value of the promise when it becomes fulfilled, returning a promise for that same value, perhaps deferred but not replaced by the promise returned by theonFulfilled handler.

Q("Hello, World!").delay(1000).tap(console.log).then(function(message){expect(message).toBe("Hello, World!");})

promise.timeout(ms, message)

Returns a promise that will have the same result aspromise, except that ifpromise is not fulfilled or rejected beforems milliseconds, the returnedpromise will be rejected with anError with the givenmessage. Ifmessageis not supplied, the message will be"Timed out after " + ms + " ms".

promise.timeout(10000).then(function(result){// will be called if the promise resolves normallyconsole.log(result);},function(err){// will be called if the promise is rejected, or the 10 second timeout occursconsole.log(err);});

promise.delay(ms)

Returns a promise that will have the same result aspromise, but will only befulfilled after at leastms milliseconds have passed. Ifpromise is rejected, the resulting promise will be rejected immediately.

Q.delay(ms)

If the static version ofQ.delay is passed only a single argument, it returnsa promise that will be fulfilled withundefined after at leastmsmilliseconds have passed. (If it's called with two arguments, it uses the usualstatic-counterpart translation, i.e.Q.delay(value, ms) is equivalent toQ(value).delay(ms).)

This is a convenient way to insert a delay into a promise chain, or even simplyto get a nicer syntax forsetTimeout:

Q.delay(150).then(doSomething);

State Inspection Methods

promise.isFulfilled()

Returns whether a given promise is in the fulfilled state. When the staticversion is used on non-promises, the result is alwaystrue.

promise.isRejected()

Returns whether a given promise is in the rejected state. When the staticversion is used on non-promises, the result is alwaysfalse.

promise.isPending()

Returns whether a given promise is in the pending state. When the static versionis used on non-promises, the result is alwaysfalse.

promise.inspect()

Returns a "state snapshot" object, which will be in one of three forms:

  • { state: "pending" }
  • { state: "fulfilled", value: <fulfllment value> }
  • { state: "rejected", reason: <rejection reason> }

Promise Creation

Q.defer()

Returns a "deferred" object with a:

  • promise property
  • resolve(value) method
  • reject(reason) method
  • notify(value) method
  • makeNodeResolver() method

Theresolve andreject methods control the state of thepromise property,which you can hand out to others while keeping the authority to modify its stateto yourself. Thenotify method is for progress notification, and themakeNodeResolver 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 callresolve,reject, ornotify ifpromise is already resolved will be a no-op.

Deferreds are cool because they separate the promise part from the resolverpart. So:

  • You can give the promise to any number of consumers and all of them willobserve the resolution independently. Because the capability of observing apromise is separated from the capability of resolving the promise, none of therecipients of the promise have the ability to "trick" other recipients withmisinformation (or indeed interfere with them in any way).

  • You can give the resolver to any number of producers and whoever resolves thepromise first wins. Furthermore, none of the producers can observe that theylost unless you give them the promise part too.

deferred.resolve(value)

Callingresolve with a pending promise causespromise to wait on the passedpromise, becoming fulfilled with its fulfillment value or rejected with itsrejection reason (or staying pending forever, if the passed promise does).

Callingresolve with a rejected promise causespromise to be rejected withthe passed promise's rejection reason.

Callingresolve with a fulfilled promise causespromise to be fulfilled withthe passed promise's fulfillment value.

Callingresolve with a non-promise value causespromise to be fulfilled withthat value.

deferred.reject(reason)

Callingreject with a reason causespromise to be rejected with that reason.

deferred.notify(value)

Callingnotify with a value causespromise to be notified ofprogress with that value. That is, anyonProgress handlers registered withpromise or promises derived frompromise will be called with the progressvalue.

Q object

Q(value)

Ifvalue is a Q promise, returns the promise.

Ifvalue is a promise from another library it is coerced into a Q promise (where possible).

Ifvalue is not a promise, returns a promise that is fulfilled withvalue.

Q.reject(reason)

Returns a promise that is rejected withreason.

Q.Promise(resolver)

Synchronously callsresolver(resolve, reject, notify) and returns a promisewhose state is controlled by the functions passed toresolver. This is analternative promise-creation API that has the same power as the deferredconcept, but without introducing another conceptual entity.

Ifresolver throws an exception, the returned promise will be rejected withthat thrown exception as the rejection reason.

note: In the latest github, this method is called Q.Promise, but if you are using the npm package version 0.9.7 or below, the method is called Q.promise (lowercase vs uppercase p).

Interfacing with Node.js Callbacks

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 assuch. Nevertheless, they also exist on each Q promise, in case you somehow havea promise for a Node.js-style function or for an object with Node.js-stylemethods.

Note that if a Node.js-style API calls back with more than one non-errorparameter (e.g.child_process.execFile), Q packages these into anarray as the promise's fulfillment value when doing the translation.

Q.nfbind(nodeFunc, ...args)

Alias:Q.denodeify

Creates a promise-returning function from a Node.js-style function, optionallybinding it with the given variadic arguments. An example:

varreadFile=Q.nfbind(FS.readFile);readFile("foo.txt","utf-8").done(function(text){});

Note that if you have amethod that uses the Node.js callback pattern, asopposed to just afunction, you will need to bind itsthis value beforepassing it tonfbind, like so:

varKitty=mongoose.model("Kitty");varfindKitties=Q.nfbind(Kitty.find.bind(Kitty));

The better strategy for methods would be to useQ.nbind, as shown below.

Q.nbind(nodeMethod, thisArg, ...args)

Creates a promise-returning function from a Node.js-style method, optionallybinding it with the given variadic arguments. An example:

varKitty=mongoose.model("Kitty");varfindKitties=Q.nbind(Kitty.find,Kitty);findKitties({cute:true}).done(function(theKitties){});

Q.nfapply(nodeFunc, args)

Calls a Node.js-style function with the given array of arguments, returning apromise that is fulfilled if the Node.js function calls back with a result, orrejected if it calls back with an error (or throws one synchronously). Anexample:

Q.nfapply(FS.readFile,["foo.txt","utf-8"]).done(function(text){});

Note that this example only works becauseFS.readFile is afunction exportedfrom a module, not amethod on an object. For methods, e.g.redisClient.get,you must bind the method to an instance before passing it toQ.nfapply (or,generally, as an argument to any function call):

Q.nfapply(redisClient.get.bind(redisClient),["user:1:id"]).done(function(user){});

The better strategy for methods would be to useQ.npost, as shown below.

Q.nfcall(func, ...args)

Calls a Node.js-style function with the given variadic arguments, returning apromise that is fulfilled if the Node.js function calls back with a result, orrejected if it calls back with an error (or throws one synchronously). Anexample:

Q.nfcall(FS.readFile,"foo.txt","utf-8").done(function(text){});

The same warning about functions vs. methods applies fornfcall as it does fornfapply. In this case, the better strategy would be to useQ.ninvoke.

Q.npost(object, methodName, args)

Deprecated Alias:Q.nmapply

Calls a Node.js-style method with the given arguments array, returning a promisethat is fulfilled if the method calls back with a result, or rejected if itcalls back with an error (or throws one synchronously). An example:

Q.npost(redisClient,"get",["user:1:id"]).done(function(user){});

Q.ninvoke(object, methodName, ...args)

Alias:Q.nsend

Deprecated Alias:Q.nmcall

Calls a Node.js-style method with the given variadic arguments, returning apromise that is fulfilled if the method calls back with a result, or rejected ifit calls back with an error (or throws one synchronously). An example:

Q.ninvoke(redisClient,"get","user:1:id").done(function(user){});

promise.nodeify(callback)

Ifcallback is a function, assumes it's a Node.js-style callback, and calls itas eithercallback(rejectionReason) when/ifpromise becomes rejected, orascallback(null, fulfillmentValue) when/ifpromise becomes fulfilled. Ifcallback is not a function, simply returnspromise.

This method is useful for creating dual promise/callback APIs, i.e. APIs thatreturn promises but also accept Node.js-style callbacks. For example:

functioncreateUser(userName,userData,callback){returndatabase.ensureUserNameNotTaken(userName).then(function(){returndatabase.saveUserData(userName,userData);}).nodeify(callback);}

deferred.makeNodeResolver()

Returns a function suitable for passing to a Node.js API. That is, it has asignature(err, result) and will rejectdeferred.promise witherr iferr is given, or fulfill it withresult if that is given.

Generators

This functionality is experimental.

Q.async(generatorFunction)

This is an experimental tool for converting a generator function into a deferredfunction. This has the potential of reducing nested callbacks in engines thatsupportyield. Seethe generators example for further information.

Q.spawn(generatorFunction)

This immediately runs a generator function, and forwards any uncaught errors toQ.onerror. An uncaught error is deemed to occur if the function returns arejected promise. Note that this automatically occurs if the generator functionthrows an error, e.g. byyielding on a promise that becomes rejected without surrounding that code with atry/catch:

Q.spawn(function*(){// If `createUser` returns a rejected promise, the rejection reason will// reach `Q.onerror`.varuser=yieldcreateUser();showUserInUI(user);});

Error Handling and Tracking

Q.onerror

A settable property that will intercept any uncaught errors that would otherwisebe thrown in the next tick of the event loop, usually as a result ofdone.Can be useful for getting the full stack trace of an error in browsers, which isnot usually possible withwindow.onerror.

Q.getUnhandledReasons()

Gets an array of reasons belonging to rejected promises that currently have notbeen handled, i.e. noonRejected callbacks have been called for them, theyhaven't been chained off of, etc. Generally these represent potentially-"lost"errors, so this array should be empty except possibly at times when you arepassing a rejected promise around asynchronously so that someone can handle therejection later.

Q.stopUnhandledRejectionTracking()

Turns off unhandled rejection tracking, which provides a slight efficiencyboost if you don't find that debug information helpful. It also prevents Q fromprinting any unhandled rejection reasons upon process exit in Node.js.

Q.resetUnhandledRejections()

Resets Q's internal tracking of unhandled rejections, but keeps unhandledrejection tracking on. This method is exposed mainly for testing and diagnosticpurposes, where you may have accumulated some unhandled rejections but want tore-start with a clean slate.

Other

Q.isPromise(value)

Returns whether the given value is a Q promise.

Q.isPromiseAlike(value)

Returns whether the given value is a promise (i.e. it's an object with athen function).

Q.promised(func)

Creates a new version offunc that accepts any combination of promise andnon-promise values, converting them to their fulfillment values before callingthe originalfunc. The returned version also always returns a promise: iffunc does areturn orthrow, thenQ.promised(func) will returnfulfilled or rejected promise, respectively.

This can be useful for creating functions that accept either promises ornon-promise values, and for ensuring that the function always returns a promiseeven in the face of unintentional thrown exceptions.

Q.longStackSupport

A settable property that lets you turn on long stack trace support. If turnedon, "stack jumps" will be tracked across asynchronous promise operations, sothat if an uncaught error is thrown bydone or a rejection reason'sstackproperty is inspected in a rejection callback, a long stack trace is produced.

Custom Messaging API (Advanced)

TheQ promise constructor establishes the basic API for performing operationson objects: "get", "put", "del", "post", "apply", and "keys". This set of"operators" can be extended by creating promises that respond to messages withother operator names, and by sending corresponding messages to those promises.

promise.dispatch(operator, args)

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 holeswhen forwarding messages to promises. The functions above, particularlythen,are carefully crafted to prevent a poorly crafted or malicious promise frombreaking the invariants like not applying callbacks multiple times or in thesame turn of the event loop.

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp