react / react-0.13.3 / examples / basic-commonjs / node_modules / reactify / node_modules / react-tools / node_modules / commoner / node_modules / q / q.js
81164 views// vim:ts=4:sts=4:sw=4:1/*!2*3* Copyright 2009-2012 Kris Kowal under the terms of the MIT4* license found at http://github.com/kriskowal/q/raw/master/LICENSE5*6* With parts by Tyler Close7* Copyright 2007-2009 Tyler Close under the terms of the MIT X license found8* at http://www.opensource.org/licenses/mit-license.html9* Forked at ref_send.js version: 2009-05-1110*11* With parts by Mark Miller12* Copyright (C) 2011 Google Inc.13*14* Licensed under the Apache License, Version 2.0 (the "License");15* you may not use this file except in compliance with the License.16* You may obtain a copy of the License at17*18* http://www.apache.org/licenses/LICENSE-2.019*20* Unless required by applicable law or agreed to in writing, software21* distributed under the License is distributed on an "AS IS" BASIS,22* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.23* See the License for the specific language governing permissions and24* limitations under the License.25*26*/2728(function (definition) {29"use strict";3031// This file will function properly as a <script> tag, or a module32// using CommonJS and NodeJS or RequireJS module formats. In33// Common/Node/RequireJS, the module exports the Q API and when34// executed as a simple <script>, it creates a Q global instead.3536// Montage Require37if (typeof bootstrap === "function") {38bootstrap("promise", definition);3940// CommonJS41} else if (typeof exports === "object" && typeof module === "object") {42module.exports = definition();4344// RequireJS45} else if (typeof define === "function" && define.amd) {46define(definition);4748// SES (Secure EcmaScript)49} else if (typeof ses !== "undefined") {50if (!ses.ok()) {51return;52} else {53ses.makeQ = definition;54}5556// <script>57} else if (typeof self !== "undefined") {58self.Q = definition();5960} else {61throw new Error("This environment was not anticiapted by Q. Please file a bug.");62}6364})(function () {65"use strict";6667var hasStacks = false;68try {69throw new Error();70} catch (e) {71hasStacks = !!e.stack;72}7374// All code after this point will be filtered from stack traces reported75// by Q.76var qStartingLine = captureLine();77var qFileName;7879// shims8081// used for fallback in "allResolved"82var noop = function () {};8384// Use the fastest possible means to execute a task in a future turn85// of the event loop.86var nextTick =(function () {87// linked list of tasks (single, with head node)88var head = {task: void 0, next: null};89var tail = head;90var flushing = false;91var requestTick = void 0;92var isNodeJS = false;9394function flush() {95/* jshint loopfunc: true */9697while (head.next) {98head = head.next;99var task = head.task;100head.task = void 0;101var domain = head.domain;102103if (domain) {104head.domain = void 0;105domain.enter();106}107108try {109task();110111} catch (e) {112if (isNodeJS) {113// In node, uncaught exceptions are considered fatal errors.114// Re-throw them synchronously to interrupt flushing!115116// Ensure continuation if the uncaught exception is suppressed117// listening "uncaughtException" events (as domains does).118// Continue in next event to avoid tick recursion.119if (domain) {120domain.exit();121}122setTimeout(flush, 0);123if (domain) {124domain.enter();125}126127throw e;128129} else {130// In browsers, uncaught exceptions are not fatal.131// Re-throw them asynchronously to avoid slow-downs.132setTimeout(function() {133throw e;134}, 0);135}136}137138if (domain) {139domain.exit();140}141}142143flushing = false;144}145146nextTick = function (task) {147tail = tail.next = {148task: task,149domain: isNodeJS && process.domain,150next: null151};152153if (!flushing) {154flushing = true;155requestTick();156}157};158159if (typeof process !== "undefined" && process.nextTick) {160// Node.js before 0.9. Note that some fake-Node environments, like the161// Mocha test runner, introduce a `process` global without a `nextTick`.162isNodeJS = true;163164requestTick = function () {165process.nextTick(flush);166};167168} else if (typeof setImmediate === "function") {169// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate170if (typeof window !== "undefined") {171requestTick = setImmediate.bind(window, flush);172} else {173requestTick = function () {174setImmediate(flush);175};176}177178} else if (typeof MessageChannel !== "undefined") {179// modern browsers180// http://www.nonblocking.io/2011/06/windownexttick.html181var channel = new MessageChannel();182// At least Safari Version 6.0.5 (8536.30.1) intermittently cannot create183// working message ports the first time a page loads.184channel.port1.onmessage = function () {185requestTick = requestPortTick;186channel.port1.onmessage = flush;187flush();188};189var requestPortTick = function () {190// Opera requires us to provide a message payload, regardless of191// whether we use it.192channel.port2.postMessage(0);193};194requestTick = function () {195setTimeout(flush, 0);196requestPortTick();197};198199} else {200// old browsers201requestTick = function () {202setTimeout(flush, 0);203};204}205206return nextTick;207})();208209// Attempt to make generics safe in the face of downstream210// modifications.211// There is no situation where this is necessary.212// If you need a security guarantee, these primordials need to be213// deeply frozen anyway, and if you don’t need a security guarantee,214// this is just plain paranoid.215// However, this **might** have the nice side-effect of reducing the size of216// the minified code by reducing x.call() to merely x()217// See Mark Miller’s explanation of what this does.218// http://wiki.ecmascript.org/doku.php?id=conventions:safe_meta_programming219var call = Function.call;220function uncurryThis(f) {221return function () {222return call.apply(f, arguments);223};224}225// This is equivalent, but slower:226// uncurryThis = Function_bind.bind(Function_bind.call);227// http://jsperf.com/uncurrythis228229var array_slice = uncurryThis(Array.prototype.slice);230231var array_reduce = uncurryThis(232Array.prototype.reduce || function (callback, basis) {233var index = 0,234length = this.length;235// concerning the initial value, if one is not provided236if (arguments.length === 1) {237// seek to the first value in the array, accounting238// for the possibility that is is a sparse array239do {240if (index in this) {241basis = this[index++];242break;243}244if (++index >= length) {245throw new TypeError();246}247} while (1);248}249// reduce250for (; index < length; index++) {251// account for the possibility that the array is sparse252if (index in this) {253basis = callback(basis, this[index], index);254}255}256return basis;257}258);259260var array_indexOf = uncurryThis(261Array.prototype.indexOf || function (value) {262// not a very good shim, but good enough for our one use of it263for (var i = 0; i < this.length; i++) {264if (this[i] === value) {265return i;266}267}268return -1;269}270);271272var array_map = uncurryThis(273Array.prototype.map || function (callback, thisp) {274var self = this;275var collect = [];276array_reduce(self, function (undefined, value, index) {277collect.push(callback.call(thisp, value, index, self));278}, void 0);279return collect;280}281);282283var object_create = Object.create || function (prototype) {284function Type() { }285Type.prototype = prototype;286return new Type();287};288289var object_hasOwnProperty = uncurryThis(Object.prototype.hasOwnProperty);290291var object_keys = Object.keys || function (object) {292var keys = [];293for (var key in object) {294if (object_hasOwnProperty(object, key)) {295keys.push(key);296}297}298return keys;299};300301var object_toString = uncurryThis(Object.prototype.toString);302303function isObject(value) {304return value === Object(value);305}306307// generator related shims308309// FIXME: Remove this function once ES6 generators are in SpiderMonkey.310function isStopIteration(exception) {311return (312object_toString(exception) === "[object StopIteration]" ||313exception instanceof QReturnValue314);315}316317// FIXME: Remove this helper and Q.return once ES6 generators are in318// SpiderMonkey.319var QReturnValue;320if (typeof ReturnValue !== "undefined") {321QReturnValue = ReturnValue;322} else {323QReturnValue = function (value) {324this.value = value;325};326}327328// long stack traces329330var STACK_JUMP_SEPARATOR = "From previous event:";331332function makeStackTraceLong(error, promise) {333// If possible, transform the error stack trace by removing Node and Q334// cruft, then concatenating with the stack trace of `promise`. See #57.335if (hasStacks &&336promise.stack &&337typeof error === "object" &&338error !== null &&339error.stack &&340error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1341) {342var stacks = [];343for (var p = promise; !!p; p = p.source) {344if (p.stack) {345stacks.unshift(p.stack);346}347}348stacks.unshift(error.stack);349350var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");351error.stack = filterStackString(concatedStacks);352}353}354355function filterStackString(stackString) {356var lines = stackString.split("\n");357var desiredLines = [];358for (var i = 0; i < lines.length; ++i) {359var line = lines[i];360361if (!isInternalFrame(line) && !isNodeFrame(line) && line) {362desiredLines.push(line);363}364}365return desiredLines.join("\n");366}367368function isNodeFrame(stackLine) {369return stackLine.indexOf("(module.js:") !== -1 ||370stackLine.indexOf("(node.js:") !== -1;371}372373function getFileNameAndLineNumber(stackLine) {374// Named functions: "at functionName (filename:lineNumber:columnNumber)"375// In IE10 function name can have spaces ("Anonymous function") O_o376var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);377if (attempt1) {378return [attempt1[1], Number(attempt1[2])];379}380381// Anonymous functions: "at filename:lineNumber:columnNumber"382var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);383if (attempt2) {384return [attempt2[1], Number(attempt2[2])];385}386387// Firefox style: "function@filename:lineNumber or @filename:lineNumber"388var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);389if (attempt3) {390return [attempt3[1], Number(attempt3[2])];391}392}393394function isInternalFrame(stackLine) {395var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);396397if (!fileNameAndLineNumber) {398return false;399}400401var fileName = fileNameAndLineNumber[0];402var lineNumber = fileNameAndLineNumber[1];403404return fileName === qFileName &&405lineNumber >= qStartingLine &&406lineNumber <= qEndingLine;407}408409// discover own file name and line number range for filtering stack410// traces411function captureLine() {412if (!hasStacks) {413return;414}415416try {417throw new Error();418} catch (e) {419var lines = e.stack.split("\n");420var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];421var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);422if (!fileNameAndLineNumber) {423return;424}425426qFileName = fileNameAndLineNumber[0];427return fileNameAndLineNumber[1];428}429}430431function deprecate(callback, name, alternative) {432return function () {433if (typeof console !== "undefined" &&434typeof console.warn === "function") {435console.warn(name + " is deprecated, use " + alternative +436" instead.", new Error("").stack);437}438return callback.apply(callback, arguments);439};440}441442// end of shims443// beginning of real work444445/**446* Constructs a promise for an immediate reference, passes promises through, or447* coerces promises from different systems.448* @param value immediate reference or promise449*/450function Q(value) {451// If the object is already a Promise, return it directly. This enables452// the resolve function to both be used to created references from objects,453// but to tolerably coerce non-promises to promises.454if (value instanceof Promise) {455return value;456}457458// assimilate thenables459if (isPromiseAlike(value)) {460return coerce(value);461} else {462return fulfill(value);463}464}465Q.resolve = Q;466467/**468* Performs a task in a future turn of the event loop.469* @param {Function} task470*/471Q.nextTick = nextTick;472473/**474* Controls whether or not long stack traces will be on475*/476Q.longStackSupport = false;477478// enable long stacks if Q_DEBUG is set479if (typeof process === "object" && process && process.env && process.env.Q_DEBUG) {480Q.longStackSupport = true;481}482483/**484* Constructs a {promise, resolve, reject} object.485*486* `resolve` is a callback to invoke with a more resolved value for the487* promise. To fulfill the promise, invoke `resolve` with any value that is488* not a thenable. To reject the promise, invoke `resolve` with a rejected489* thenable, or invoke `reject` with the reason directly. To resolve the490* promise to another thenable, thus putting it in the same state, invoke491* `resolve` with that other thenable.492*/493Q.defer = defer;494function defer() {495// if "messages" is an "Array", that indicates that the promise has not yet496// been resolved. If it is "undefined", it has been resolved. Each497// element of the messages array is itself an array of complete arguments to498// forward to the resolved promise. We coerce the resolution value to a499// promise using the `resolve` function because it handles both fully500// non-thenable values and other thenables gracefully.501var messages = [], progressListeners = [], resolvedPromise;502503var deferred = object_create(defer.prototype);504var promise = object_create(Promise.prototype);505506promise.promiseDispatch = function (resolve, op, operands) {507var args = array_slice(arguments);508if (messages) {509messages.push(args);510if (op === "when" && operands[1]) { // progress operand511progressListeners.push(operands[1]);512}513} else {514Q.nextTick(function () {515resolvedPromise.promiseDispatch.apply(resolvedPromise, args);516});517}518};519520// XXX deprecated521promise.valueOf = function () {522if (messages) {523return promise;524}525var nearerValue = nearer(resolvedPromise);526if (isPromise(nearerValue)) {527resolvedPromise = nearerValue; // shorten chain528}529return nearerValue;530};531532promise.inspect = function () {533if (!resolvedPromise) {534return { state: "pending" };535}536return resolvedPromise.inspect();537};538539if (Q.longStackSupport && hasStacks) {540try {541throw new Error();542} catch (e) {543// NOTE: don't try to use `Error.captureStackTrace` or transfer the544// accessor around; that causes memory leaks as per GH-111. Just545// reify the stack trace as a string ASAP.546//547// At the same time, cut off the first line; it's always just548// "[object Promise]\n", as per the `toString`.549promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);550}551}552553// NOTE: we do the checks for `resolvedPromise` in each method, instead of554// consolidating them into `become`, since otherwise we'd create new555// promises with the lines `become(whatever(value))`. See e.g. GH-252.556557function become(newPromise) {558resolvedPromise = newPromise;559promise.source = newPromise;560561array_reduce(messages, function (undefined, message) {562Q.nextTick(function () {563newPromise.promiseDispatch.apply(newPromise, message);564});565}, void 0);566567messages = void 0;568progressListeners = void 0;569}570571deferred.promise = promise;572deferred.resolve = function (value) {573if (resolvedPromise) {574return;575}576577become(Q(value));578};579580deferred.fulfill = function (value) {581if (resolvedPromise) {582return;583}584585become(fulfill(value));586};587deferred.reject = function (reason) {588if (resolvedPromise) {589return;590}591592become(reject(reason));593};594deferred.notify = function (progress) {595if (resolvedPromise) {596return;597}598599array_reduce(progressListeners, function (undefined, progressListener) {600Q.nextTick(function () {601progressListener(progress);602});603}, void 0);604};605606return deferred;607}608609/**610* Creates a Node-style callback that will resolve or reject the deferred611* promise.612* @returns a nodeback613*/614defer.prototype.makeNodeResolver = function () {615var self = this;616return function (error, value) {617if (error) {618self.reject(error);619} else if (arguments.length > 2) {620self.resolve(array_slice(arguments, 1));621} else {622self.resolve(value);623}624};625};626627/**628* @param resolver {Function} a function that returns nothing and accepts629* the resolve, reject, and notify functions for a deferred.630* @returns a promise that may be resolved with the given resolve and reject631* functions, or rejected by a thrown exception in resolver632*/633Q.Promise = promise; // ES6634Q.promise = promise;635function promise(resolver) {636if (typeof resolver !== "function") {637throw new TypeError("resolver must be a function.");638}639var deferred = defer();640try {641resolver(deferred.resolve, deferred.reject, deferred.notify);642} catch (reason) {643deferred.reject(reason);644}645return deferred.promise;646}647648promise.race = race; // ES6649promise.all = all; // ES6650promise.reject = reject; // ES6651promise.resolve = Q; // ES6652653// XXX experimental. This method is a way to denote that a local value is654// serializable and should be immediately dispatched to a remote upon request,655// instead of passing a reference.656Q.passByCopy = function (object) {657//freeze(object);658//passByCopies.set(object, true);659return object;660};661662Promise.prototype.passByCopy = function () {663//freeze(object);664//passByCopies.set(object, true);665return this;666};667668/**669* If two promises eventually fulfill to the same value, promises that value,670* but otherwise rejects.671* @param x {Any*}672* @param y {Any*}673* @returns {Any*} a promise for x and y if they are the same, but a rejection674* otherwise.675*676*/677Q.join = function (x, y) {678return Q(x).join(y);679};680681Promise.prototype.join = function (that) {682return Q([this, that]).spread(function (x, y) {683if (x === y) {684// TODO: "===" should be Object.is or equiv685return x;686} else {687throw new Error("Can't join: not the same: " + x + " " + y);688}689});690};691692/**693* Returns a promise for the first of an array of promises to become settled.694* @param answers {Array[Any*]} promises to race695* @returns {Any*} the first promise to be settled696*/697Q.race = race;698function race(answerPs) {699return promise(function(resolve, reject) {700// Switch to this once we can assume at least ES5701// answerPs.forEach(function(answerP) {702// Q(answerP).then(resolve, reject);703// });704// Use this in the meantime705for (var i = 0, len = answerPs.length; i < len; i++) {706Q(answerPs[i]).then(resolve, reject);707}708});709}710711Promise.prototype.race = function () {712return this.then(Q.race);713};714715/**716* Constructs a Promise with a promise descriptor object and optional fallback717* function. The descriptor contains methods like when(rejected), get(name),718* set(name, value), post(name, args), and delete(name), which all719* return either a value, a promise for a value, or a rejection. The fallback720* accepts the operation name, a resolver, and any further arguments that would721* have been forwarded to the appropriate method above had a method been722* provided with the proper name. The API makes no guarantees about the nature723* of the returned object, apart from that it is usable whereever promises are724* bought and sold.725*/726Q.makePromise = Promise;727function Promise(descriptor, fallback, inspect) {728if (fallback === void 0) {729fallback = function (op) {730return reject(new Error(731"Promise does not support operation: " + op732));733};734}735if (inspect === void 0) {736inspect = function () {737return {state: "unknown"};738};739}740741var promise = object_create(Promise.prototype);742743promise.promiseDispatch = function (resolve, op, args) {744var result;745try {746if (descriptor[op]) {747result = descriptor[op].apply(promise, args);748} else {749result = fallback.call(promise, op, args);750}751} catch (exception) {752result = reject(exception);753}754if (resolve) {755resolve(result);756}757};758759promise.inspect = inspect;760761// XXX deprecated `valueOf` and `exception` support762if (inspect) {763var inspected = inspect();764if (inspected.state === "rejected") {765promise.exception = inspected.reason;766}767768promise.valueOf = function () {769var inspected = inspect();770if (inspected.state === "pending" ||771inspected.state === "rejected") {772return promise;773}774return inspected.value;775};776}777778return promise;779}780781Promise.prototype.toString = function () {782return "[object Promise]";783};784785Promise.prototype.then = function (fulfilled, rejected, progressed) {786var self = this;787var deferred = defer();788var done = false; // ensure the untrusted promise makes at most a789// single call to one of the callbacks790791function _fulfilled(value) {792try {793return typeof fulfilled === "function" ? fulfilled(value) : value;794} catch (exception) {795return reject(exception);796}797}798799function _rejected(exception) {800if (typeof rejected === "function") {801makeStackTraceLong(exception, self);802try {803return rejected(exception);804} catch (newException) {805return reject(newException);806}807}808return reject(exception);809}810811function _progressed(value) {812return typeof progressed === "function" ? progressed(value) : value;813}814815Q.nextTick(function () {816self.promiseDispatch(function (value) {817if (done) {818return;819}820done = true;821822deferred.resolve(_fulfilled(value));823}, "when", [function (exception) {824if (done) {825return;826}827done = true;828829deferred.resolve(_rejected(exception));830}]);831});832833// Progress propagator need to be attached in the current tick.834self.promiseDispatch(void 0, "when", [void 0, function (value) {835var newValue;836var threw = false;837try {838newValue = _progressed(value);839} catch (e) {840threw = true;841if (Q.onerror) {842Q.onerror(e);843} else {844throw e;845}846}847848if (!threw) {849deferred.notify(newValue);850}851}]);852853return deferred.promise;854};855856Q.tap = function (promise, callback) {857return Q(promise).tap(callback);858};859860/**861* Works almost like "finally", but not called for rejections.862* Original resolution value is passed through callback unaffected.863* Callback may return a promise that will be awaited for.864* @param {Function} callback865* @returns {Q.Promise}866* @example867* doSomething()868* .then(...)869* .tap(console.log)870* .then(...);871*/872Promise.prototype.tap = function (callback) {873callback = Q(callback);874875return this.then(function (value) {876return callback.fcall(value).thenResolve(value);877});878};879880/**881* Registers an observer on a promise.882*883* Guarantees:884*885* 1. that fulfilled and rejected will be called only once.886* 2. that either the fulfilled callback or the rejected callback will be887* called, but not both.888* 3. that fulfilled and rejected will not be called in this turn.889*890* @param value promise or immediate reference to observe891* @param fulfilled function to be called with the fulfilled value892* @param rejected function to be called with the rejection exception893* @param progressed function to be called on any progress notifications894* @return promise for the return value from the invoked callback895*/896Q.when = when;897function when(value, fulfilled, rejected, progressed) {898return Q(value).then(fulfilled, rejected, progressed);899}900901Promise.prototype.thenResolve = function (value) {902return this.then(function () { return value; });903};904905Q.thenResolve = function (promise, value) {906return Q(promise).thenResolve(value);907};908909Promise.prototype.thenReject = function (reason) {910return this.then(function () { throw reason; });911};912913Q.thenReject = function (promise, reason) {914return Q(promise).thenReject(reason);915};916917/**918* If an object is not a promise, it is as "near" as possible.919* If a promise is rejected, it is as "near" as possible too.920* If it’s a fulfilled promise, the fulfillment value is nearer.921* If it’s a deferred promise and the deferred has been resolved, the922* resolution is "nearer".923* @param object924* @returns most resolved (nearest) form of the object925*/926927// XXX should we re-do this?928Q.nearer = nearer;929function nearer(value) {930if (isPromise(value)) {931var inspected = value.inspect();932if (inspected.state === "fulfilled") {933return inspected.value;934}935}936return value;937}938939/**940* @returns whether the given object is a promise.941* Otherwise it is a fulfilled value.942*/943Q.isPromise = isPromise;944function isPromise(object) {945return object instanceof Promise;946}947948Q.isPromiseAlike = isPromiseAlike;949function isPromiseAlike(object) {950return isObject(object) && typeof object.then === "function";951}952953/**954* @returns whether the given object is a pending promise, meaning not955* fulfilled or rejected.956*/957Q.isPending = isPending;958function isPending(object) {959return isPromise(object) && object.inspect().state === "pending";960}961962Promise.prototype.isPending = function () {963return this.inspect().state === "pending";964};965966/**967* @returns whether the given object is a value or fulfilled968* promise.969*/970Q.isFulfilled = isFulfilled;971function isFulfilled(object) {972return !isPromise(object) || object.inspect().state === "fulfilled";973}974975Promise.prototype.isFulfilled = function () {976return this.inspect().state === "fulfilled";977};978979/**980* @returns whether the given object is a rejected promise.981*/982Q.isRejected = isRejected;983function isRejected(object) {984return isPromise(object) && object.inspect().state === "rejected";985}986987Promise.prototype.isRejected = function () {988return this.inspect().state === "rejected";989};990991//// BEGIN UNHANDLED REJECTION TRACKING992993// This promise library consumes exceptions thrown in handlers so they can be994// handled by a subsequent promise. The exceptions get added to this array when995// they are created, and removed when they are handled. Note that in ES6 or996// shimmed environments, this would naturally be a `Set`.997var unhandledReasons = [];998var unhandledRejections = [];999var trackUnhandledRejections = true;10001001function resetUnhandledRejections() {1002unhandledReasons.length = 0;1003unhandledRejections.length = 0;10041005if (!trackUnhandledRejections) {1006trackUnhandledRejections = true;1007}1008}10091010function trackRejection(promise, reason) {1011if (!trackUnhandledRejections) {1012return;1013}10141015unhandledRejections.push(promise);1016if (reason && typeof reason.stack !== "undefined") {1017unhandledReasons.push(reason.stack);1018} else {1019unhandledReasons.push("(no stack) " + reason);1020}1021}10221023function untrackRejection(promise) {1024if (!trackUnhandledRejections) {1025return;1026}10271028var at = array_indexOf(unhandledRejections, promise);1029if (at !== -1) {1030unhandledRejections.splice(at, 1);1031unhandledReasons.splice(at, 1);1032}1033}10341035Q.resetUnhandledRejections = resetUnhandledRejections;10361037Q.getUnhandledReasons = function () {1038// Make a copy so that consumers can't interfere with our internal state.1039return unhandledReasons.slice();1040};10411042Q.stopUnhandledRejectionTracking = function () {1043resetUnhandledRejections();1044trackUnhandledRejections = false;1045};10461047resetUnhandledRejections();10481049//// END UNHANDLED REJECTION TRACKING10501051/**1052* Constructs a rejected promise.1053* @param reason value describing the failure1054*/1055Q.reject = reject;1056function reject(reason) {1057var rejection = Promise({1058"when": function (rejected) {1059// note that the error has been handled1060if (rejected) {1061untrackRejection(this);1062}1063return rejected ? rejected(reason) : this;1064}1065}, function fallback() {1066return this;1067}, function inspect() {1068return { state: "rejected", reason: reason };1069});10701071// Note that the reason has not been handled.1072trackRejection(rejection, reason);10731074return rejection;1075}10761077/**1078* Constructs a fulfilled promise for an immediate reference.1079* @param value immediate reference1080*/1081Q.fulfill = fulfill;1082function fulfill(value) {1083return Promise({1084"when": function () {1085return value;1086},1087"get": function (name) {1088return value[name];1089},1090"set": function (name, rhs) {1091value[name] = rhs;1092},1093"delete": function (name) {1094delete value[name];1095},1096"post": function (name, args) {1097// Mark Miller proposes that post with no name should apply a1098// promised function.1099if (name === null || name === void 0) {1100return value.apply(void 0, args);1101} else {1102return value[name].apply(value, args);1103}1104},1105"apply": function (thisp, args) {1106return value.apply(thisp, args);1107},1108"keys": function () {1109return object_keys(value);1110}1111}, void 0, function inspect() {1112return { state: "fulfilled", value: value };1113});1114}11151116/**1117* Converts thenables to Q promises.1118* @param promise thenable promise1119* @returns a Q promise1120*/1121function coerce(promise) {1122var deferred = defer();1123Q.nextTick(function () {1124try {1125promise.then(deferred.resolve, deferred.reject, deferred.notify);1126} catch (exception) {1127deferred.reject(exception);1128}1129});1130return deferred.promise;1131}11321133/**1134* Annotates an object such that it will never be1135* transferred away from this process over any promise1136* communication channel.1137* @param object1138* @returns promise a wrapping of that object that1139* additionally responds to the "isDef" message1140* without a rejection.1141*/1142Q.master = master;1143function master(object) {1144return Promise({1145"isDef": function () {}1146}, function fallback(op, args) {1147return dispatch(object, op, args);1148}, function () {1149return Q(object).inspect();1150});1151}11521153/**1154* Spreads the values of a promised array of arguments into the1155* fulfillment callback.1156* @param fulfilled callback that receives variadic arguments from the1157* promised array1158* @param rejected callback that receives the exception if the promise1159* is rejected.1160* @returns a promise for the return value or thrown exception of1161* either callback.1162*/1163Q.spread = spread;1164function spread(value, fulfilled, rejected) {1165return Q(value).spread(fulfilled, rejected);1166}11671168Promise.prototype.spread = function (fulfilled, rejected) {1169return this.all().then(function (array) {1170return fulfilled.apply(void 0, array);1171}, rejected);1172};11731174/**1175* The async function is a decorator for generator functions, turning1176* them into asynchronous generators. Although generators are only part1177* of the newest ECMAScript 6 drafts, this code does not cause syntax1178* errors in older engines. This code should continue to work and will1179* in fact improve over time as the language improves.1180*1181* ES6 generators are currently part of V8 version 3.19 with the1182* --harmony-generators runtime flag enabled. SpiderMonkey has had them1183* for longer, but under an older Python-inspired form. This function1184* works on both kinds of generators.1185*1186* Decorates a generator function such that:1187* - it may yield promises1188* - execution will continue when that promise is fulfilled1189* - the value of the yield expression will be the fulfilled value1190* - it returns a promise for the return value (when the generator1191* stops iterating)1192* - the decorated function returns a promise for the return value1193* of the generator or the first rejected promise among those1194* yielded.1195* - if an error is thrown in the generator, it propagates through1196* every following yield until it is caught, or until it escapes1197* the generator function altogether, and is translated into a1198* rejection for the promise returned by the decorated generator.1199*/1200Q.async = async;1201function async(makeGenerator) {1202return function () {1203// when verb is "send", arg is a value1204// when verb is "throw", arg is an exception1205function continuer(verb, arg) {1206var result;12071208// Until V8 3.19 / Chromium 29 is released, SpiderMonkey is the only1209// engine that has a deployed base of browsers that support generators.1210// However, SM's generators use the Python-inspired semantics of1211// outdated ES6 drafts. We would like to support ES6, but we'd also1212// like to make it possible to use generators in deployed browsers, so1213// we also support Python-style generators. At some point we can remove1214// this block.12151216if (typeof StopIteration === "undefined") {1217// ES6 Generators1218try {1219result = generator[verb](arg);1220} catch (exception) {1221return reject(exception);1222}1223if (result.done) {1224return Q(result.value);1225} else {1226return when(result.value, callback, errback);1227}1228} else {1229// SpiderMonkey Generators1230// FIXME: Remove this case when SM does ES6 generators.1231try {1232result = generator[verb](arg);1233} catch (exception) {1234if (isStopIteration(exception)) {1235return Q(exception.value);1236} else {1237return reject(exception);1238}1239}1240return when(result, callback, errback);1241}1242}1243var generator = makeGenerator.apply(this, arguments);1244var callback = continuer.bind(continuer, "next");1245var errback = continuer.bind(continuer, "throw");1246return callback();1247};1248}12491250/**1251* The spawn function is a small wrapper around async that immediately1252* calls the generator and also ends the promise chain, so that any1253* unhandled errors are thrown instead of forwarded to the error1254* handler. This is useful because it's extremely common to run1255* generators at the top-level to work with libraries.1256*/1257Q.spawn = spawn;1258function spawn(makeGenerator) {1259Q.done(Q.async(makeGenerator)());1260}12611262// FIXME: Remove this interface once ES6 generators are in SpiderMonkey.1263/**1264* Throws a ReturnValue exception to stop an asynchronous generator.1265*1266* This interface is a stop-gap measure to support generator return1267* values in older Firefox/SpiderMonkey. In browsers that support ES61268* generators like Chromium 29, just use "return" in your generator1269* functions.1270*1271* @param value the return value for the surrounding generator1272* @throws ReturnValue exception with the value.1273* @example1274* // ES6 style1275* Q.async(function* () {1276* var foo = yield getFooPromise();1277* var bar = yield getBarPromise();1278* return foo + bar;1279* })1280* // Older SpiderMonkey style1281* Q.async(function () {1282* var foo = yield getFooPromise();1283* var bar = yield getBarPromise();1284* Q.return(foo + bar);1285* })1286*/1287Q["return"] = _return;1288function _return(value) {1289throw new QReturnValue(value);1290}12911292/**1293* The promised function decorator ensures that any promise arguments1294* are settled and passed as values (`this` is also settled and passed1295* as a value). It will also ensure that the result of a function is1296* always a promise.1297*1298* @example1299* var add = Q.promised(function (a, b) {1300* return a + b;1301* });1302* add(Q(a), Q(B));1303*1304* @param {function} callback The function to decorate1305* @returns {function} a function that has been decorated.1306*/1307Q.promised = promised;1308function promised(callback) {1309return function () {1310return spread([this, all(arguments)], function (self, args) {1311return callback.apply(self, args);1312});1313};1314}13151316/**1317* sends a message to a value in a future turn1318* @param object* the recipient1319* @param op the name of the message operation, e.g., "when",1320* @param args further arguments to be forwarded to the operation1321* @returns result {Promise} a promise for the result of the operation1322*/1323Q.dispatch = dispatch;1324function dispatch(object, op, args) {1325return Q(object).dispatch(op, args);1326}13271328Promise.prototype.dispatch = function (op, args) {1329var self = this;1330var deferred = defer();1331Q.nextTick(function () {1332self.promiseDispatch(deferred.resolve, op, args);1333});1334return deferred.promise;1335};13361337/**1338* Gets the value of a property in a future turn.1339* @param object promise or immediate reference for target object1340* @param name name of property to get1341* @return promise for the property value1342*/1343Q.get = function (object, key) {1344return Q(object).dispatch("get", [key]);1345};13461347Promise.prototype.get = function (key) {1348return this.dispatch("get", [key]);1349};13501351/**1352* Sets the value of a property in a future turn.1353* @param object promise or immediate reference for object object1354* @param name name of property to set1355* @param value new value of property1356* @return promise for the return value1357*/1358Q.set = function (object, key, value) {1359return Q(object).dispatch("set", [key, value]);1360};13611362Promise.prototype.set = function (key, value) {1363return this.dispatch("set", [key, value]);1364};13651366/**1367* Deletes a property in a future turn.1368* @param object promise or immediate reference for target object1369* @param name name of property to delete1370* @return promise for the return value1371*/1372Q.del = // XXX legacy1373Q["delete"] = function (object, key) {1374return Q(object).dispatch("delete", [key]);1375};13761377Promise.prototype.del = // XXX legacy1378Promise.prototype["delete"] = function (key) {1379return this.dispatch("delete", [key]);1380};13811382/**1383* Invokes a method in a future turn.1384* @param object promise or immediate reference for target object1385* @param name name of method to invoke1386* @param value a value to post, typically an array of1387* invocation arguments for promises that1388* are ultimately backed with `resolve` values,1389* as opposed to those backed with URLs1390* wherein the posted value can be any1391* JSON serializable object.1392* @return promise for the return value1393*/1394// bound locally because it is used by other methods1395Q.mapply = // XXX As proposed by "Redsandro"1396Q.post = function (object, name, args) {1397return Q(object).dispatch("post", [name, args]);1398};13991400Promise.prototype.mapply = // XXX As proposed by "Redsandro"1401Promise.prototype.post = function (name, args) {1402return this.dispatch("post", [name, args]);1403};14041405/**1406* Invokes a method in a future turn.1407* @param object promise or immediate reference for target object1408* @param name name of method to invoke1409* @param ...args array of invocation arguments1410* @return promise for the return value1411*/1412Q.send = // XXX Mark Miller's proposed parlance1413Q.mcall = // XXX As proposed by "Redsandro"1414Q.invoke = function (object, name /*...args*/) {1415return Q(object).dispatch("post", [name, array_slice(arguments, 2)]);1416};14171418Promise.prototype.send = // XXX Mark Miller's proposed parlance1419Promise.prototype.mcall = // XXX As proposed by "Redsandro"1420Promise.prototype.invoke = function (name /*...args*/) {1421return this.dispatch("post", [name, array_slice(arguments, 1)]);1422};14231424/**1425* Applies the promised function in a future turn.1426* @param object promise or immediate reference for target function1427* @param args array of application arguments1428*/1429Q.fapply = function (object, args) {1430return Q(object).dispatch("apply", [void 0, args]);1431};14321433Promise.prototype.fapply = function (args) {1434return this.dispatch("apply", [void 0, args]);1435};14361437/**1438* Calls the promised function in a future turn.1439* @param object promise or immediate reference for target function1440* @param ...args array of application arguments1441*/1442Q["try"] =1443Q.fcall = function (object /* ...args*/) {1444return Q(object).dispatch("apply", [void 0, array_slice(arguments, 1)]);1445};14461447Promise.prototype.fcall = function (/*...args*/) {1448return this.dispatch("apply", [void 0, array_slice(arguments)]);1449};14501451/**1452* Binds the promised function, transforming return values into a fulfilled1453* promise and thrown errors into a rejected one.1454* @param object promise or immediate reference for target function1455* @param ...args array of application arguments1456*/1457Q.fbind = function (object /*...args*/) {1458var promise = Q(object);1459var args = array_slice(arguments, 1);1460return function fbound() {1461return promise.dispatch("apply", [1462this,1463args.concat(array_slice(arguments))1464]);1465};1466};1467Promise.prototype.fbind = function (/*...args*/) {1468var promise = this;1469var args = array_slice(arguments);1470return function fbound() {1471return promise.dispatch("apply", [1472this,1473args.concat(array_slice(arguments))1474]);1475};1476};14771478/**1479* Requests the names of the owned properties of a promised1480* object in a future turn.1481* @param object promise or immediate reference for target object1482* @return promise for the keys of the eventually settled object1483*/1484Q.keys = function (object) {1485return Q(object).dispatch("keys", []);1486};14871488Promise.prototype.keys = function () {1489return this.dispatch("keys", []);1490};14911492/**1493* Turns an array of promises into a promise for an array. If any of1494* the promises gets rejected, the whole array is rejected immediately.1495* @param {Array*} an array (or promise for an array) of values (or1496* promises for values)1497* @returns a promise for an array of the corresponding values1498*/1499// By Mark Miller1500// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled1501Q.all = all;1502function all(promises) {1503return when(promises, function (promises) {1504var countDown = 0;1505var deferred = defer();1506array_reduce(promises, function (undefined, promise, index) {1507var snapshot;1508if (1509isPromise(promise) &&1510(snapshot = promise.inspect()).state === "fulfilled"1511) {1512promises[index] = snapshot.value;1513} else {1514++countDown;1515when(1516promise,1517function (value) {1518promises[index] = value;1519if (--countDown === 0) {1520deferred.resolve(promises);1521}1522},1523deferred.reject,1524function (progress) {1525deferred.notify({ index: index, value: progress });1526}1527);1528}1529}, void 0);1530if (countDown === 0) {1531deferred.resolve(promises);1532}1533return deferred.promise;1534});1535}15361537Promise.prototype.all = function () {1538return all(this);1539};15401541/**1542* Waits for all promises to be settled, either fulfilled or1543* rejected. This is distinct from `all` since that would stop1544* waiting at the first rejection. The promise returned by1545* `allResolved` will never be rejected.1546* @param promises a promise for an array (or an array) of promises1547* (or values)1548* @return a promise for an array of promises1549*/1550Q.allResolved = deprecate(allResolved, "allResolved", "allSettled");1551function allResolved(promises) {1552return when(promises, function (promises) {1553promises = array_map(promises, Q);1554return when(all(array_map(promises, function (promise) {1555return when(promise, noop, noop);1556})), function () {1557return promises;1558});1559});1560}15611562Promise.prototype.allResolved = function () {1563return allResolved(this);1564};15651566/**1567* @see Promise#allSettled1568*/1569Q.allSettled = allSettled;1570function allSettled(promises) {1571return Q(promises).allSettled();1572}15731574/**1575* Turns an array of promises into a promise for an array of their states (as1576* returned by `inspect`) when they have all settled.1577* @param {Array[Any*]} values an array (or promise for an array) of values (or1578* promises for values)1579* @returns {Array[State]} an array of states for the respective values.1580*/1581Promise.prototype.allSettled = function () {1582return this.then(function (promises) {1583return all(array_map(promises, function (promise) {1584promise = Q(promise);1585function regardless() {1586return promise.inspect();1587}1588return promise.then(regardless, regardless);1589}));1590});1591};15921593/**1594* Captures the failure of a promise, giving an oportunity to recover1595* with a callback. If the given promise is fulfilled, the returned1596* promise is fulfilled.1597* @param {Any*} promise for something1598* @param {Function} callback to fulfill the returned promise if the1599* given promise is rejected1600* @returns a promise for the return value of the callback1601*/1602Q.fail = // XXX legacy1603Q["catch"] = function (object, rejected) {1604return Q(object).then(void 0, rejected);1605};16061607Promise.prototype.fail = // XXX legacy1608Promise.prototype["catch"] = function (rejected) {1609return this.then(void 0, rejected);1610};16111612/**1613* Attaches a listener that can respond to progress notifications from a1614* promise's originating deferred. This listener receives the exact arguments1615* passed to ``deferred.notify``.1616* @param {Any*} promise for something1617* @param {Function} callback to receive any progress notifications1618* @returns the given promise, unchanged1619*/1620Q.progress = progress;1621function progress(object, progressed) {1622return Q(object).then(void 0, void 0, progressed);1623}16241625Promise.prototype.progress = function (progressed) {1626return this.then(void 0, void 0, progressed);1627};16281629/**1630* Provides an opportunity to observe the settling of a promise,1631* regardless of whether the promise is fulfilled or rejected. Forwards1632* the resolution to the returned promise when the callback is done.1633* The callback can return a promise to defer completion.1634* @param {Any*} promise1635* @param {Function} callback to observe the resolution of the given1636* promise, takes no arguments.1637* @returns a promise for the resolution of the given promise when1638* ``fin`` is done.1639*/1640Q.fin = // XXX legacy1641Q["finally"] = function (object, callback) {1642return Q(object)["finally"](callback);1643};16441645Promise.prototype.fin = // XXX legacy1646Promise.prototype["finally"] = function (callback) {1647callback = Q(callback);1648return this.then(function (value) {1649return callback.fcall().then(function () {1650return value;1651});1652}, function (reason) {1653// TODO attempt to recycle the rejection with "this".1654return callback.fcall().then(function () {1655throw reason;1656});1657});1658};16591660/**1661* Terminates a chain of promises, forcing rejections to be1662* thrown as exceptions.1663* @param {Any*} promise at the end of a chain of promises1664* @returns nothing1665*/1666Q.done = function (object, fulfilled, rejected, progress) {1667return Q(object).done(fulfilled, rejected, progress);1668};16691670Promise.prototype.done = function (fulfilled, rejected, progress) {1671var onUnhandledError = function (error) {1672// forward to a future turn so that ``when``1673// does not catch it and turn it into a rejection.1674Q.nextTick(function () {1675makeStackTraceLong(error, promise);1676if (Q.onerror) {1677Q.onerror(error);1678} else {1679throw error;1680}1681});1682};16831684// Avoid unnecessary `nextTick`ing via an unnecessary `when`.1685var promise = fulfilled || rejected || progress ?1686this.then(fulfilled, rejected, progress) :1687this;16881689if (typeof process === "object" && process && process.domain) {1690onUnhandledError = process.domain.bind(onUnhandledError);1691}16921693promise.then(void 0, onUnhandledError);1694};16951696/**1697* Causes a promise to be rejected if it does not get fulfilled before1698* some milliseconds time out.1699* @param {Any*} promise1700* @param {Number} milliseconds timeout1701* @param {Any*} custom error message or Error object (optional)1702* @returns a promise for the resolution of the given promise if it is1703* fulfilled before the timeout, otherwise rejected.1704*/1705Q.timeout = function (object, ms, error) {1706return Q(object).timeout(ms, error);1707};17081709Promise.prototype.timeout = function (ms, error) {1710var deferred = defer();1711var timeoutId = setTimeout(function () {1712if (!error || "string" === typeof error) {1713error = new Error(error || "Timed out after " + ms + " ms");1714error.code = "ETIMEDOUT";1715}1716deferred.reject(error);1717}, ms);17181719this.then(function (value) {1720clearTimeout(timeoutId);1721deferred.resolve(value);1722}, function (exception) {1723clearTimeout(timeoutId);1724deferred.reject(exception);1725}, deferred.notify);17261727return deferred.promise;1728};17291730/**1731* Returns a promise for the given value (or promised value), some1732* milliseconds after it resolved. Passes rejections immediately.1733* @param {Any*} promise1734* @param {Number} milliseconds1735* @returns a promise for the resolution of the given promise after milliseconds1736* time has elapsed since the resolution of the given promise.1737* If the given promise rejects, that is passed immediately.1738*/1739Q.delay = function (object, timeout) {1740if (timeout === void 0) {1741timeout = object;1742object = void 0;1743}1744return Q(object).delay(timeout);1745};17461747Promise.prototype.delay = function (timeout) {1748return this.then(function (value) {1749var deferred = defer();1750setTimeout(function () {1751deferred.resolve(value);1752}, timeout);1753return deferred.promise;1754});1755};17561757/**1758* Passes a continuation to a Node function, which is called with the given1759* arguments provided as an array, and returns a promise.1760*1761* Q.nfapply(FS.readFile, [__filename])1762* .then(function (content) {1763* })1764*1765*/1766Q.nfapply = function (callback, args) {1767return Q(callback).nfapply(args);1768};17691770Promise.prototype.nfapply = function (args) {1771var deferred = defer();1772var nodeArgs = array_slice(args);1773nodeArgs.push(deferred.makeNodeResolver());1774this.fapply(nodeArgs).fail(deferred.reject);1775return deferred.promise;1776};17771778/**1779* Passes a continuation to a Node function, which is called with the given1780* arguments provided individually, and returns a promise.1781* @example1782* Q.nfcall(FS.readFile, __filename)1783* .then(function (content) {1784* })1785*1786*/1787Q.nfcall = function (callback /*...args*/) {1788var args = array_slice(arguments, 1);1789return Q(callback).nfapply(args);1790};17911792Promise.prototype.nfcall = function (/*...args*/) {1793var nodeArgs = array_slice(arguments);1794var deferred = defer();1795nodeArgs.push(deferred.makeNodeResolver());1796this.fapply(nodeArgs).fail(deferred.reject);1797return deferred.promise;1798};17991800/**1801* Wraps a NodeJS continuation passing function and returns an equivalent1802* version that returns a promise.1803* @example1804* Q.nfbind(FS.readFile, __filename)("utf-8")1805* .then(console.log)1806* .done()1807*/1808Q.nfbind =1809Q.denodeify = function (callback /*...args*/) {1810var baseArgs = array_slice(arguments, 1);1811return function () {1812var nodeArgs = baseArgs.concat(array_slice(arguments));1813var deferred = defer();1814nodeArgs.push(deferred.makeNodeResolver());1815Q(callback).fapply(nodeArgs).fail(deferred.reject);1816return deferred.promise;1817};1818};18191820Promise.prototype.nfbind =1821Promise.prototype.denodeify = function (/*...args*/) {1822var args = array_slice(arguments);1823args.unshift(this);1824return Q.denodeify.apply(void 0, args);1825};18261827Q.nbind = function (callback, thisp /*...args*/) {1828var baseArgs = array_slice(arguments, 2);1829return function () {1830var nodeArgs = baseArgs.concat(array_slice(arguments));1831var deferred = defer();1832nodeArgs.push(deferred.makeNodeResolver());1833function bound() {1834return callback.apply(thisp, arguments);1835}1836Q(bound).fapply(nodeArgs).fail(deferred.reject);1837return deferred.promise;1838};1839};18401841Promise.prototype.nbind = function (/*thisp, ...args*/) {1842var args = array_slice(arguments, 0);1843args.unshift(this);1844return Q.nbind.apply(void 0, args);1845};18461847/**1848* Calls a method of a Node-style object that accepts a Node-style1849* callback with a given array of arguments, plus a provided callback.1850* @param object an object that has the named method1851* @param {String} name name of the method of object1852* @param {Array} args arguments to pass to the method; the callback1853* will be provided by Q and appended to these arguments.1854* @returns a promise for the value or error1855*/1856Q.nmapply = // XXX As proposed by "Redsandro"1857Q.npost = function (object, name, args) {1858return Q(object).npost(name, args);1859};18601861Promise.prototype.nmapply = // XXX As proposed by "Redsandro"1862Promise.prototype.npost = function (name, args) {1863var nodeArgs = array_slice(args || []);1864var deferred = defer();1865nodeArgs.push(deferred.makeNodeResolver());1866this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);1867return deferred.promise;1868};18691870/**1871* Calls a method of a Node-style object that accepts a Node-style1872* callback, forwarding the given variadic arguments, plus a provided1873* callback argument.1874* @param object an object that has the named method1875* @param {String} name name of the method of object1876* @param ...args arguments to pass to the method; the callback will1877* be provided by Q and appended to these arguments.1878* @returns a promise for the value or error1879*/1880Q.nsend = // XXX Based on Mark Miller's proposed "send"1881Q.nmcall = // XXX Based on "Redsandro's" proposal1882Q.ninvoke = function (object, name /*...args*/) {1883var nodeArgs = array_slice(arguments, 2);1884var deferred = defer();1885nodeArgs.push(deferred.makeNodeResolver());1886Q(object).dispatch("post", [name, nodeArgs]).fail(deferred.reject);1887return deferred.promise;1888};18891890Promise.prototype.nsend = // XXX Based on Mark Miller's proposed "send"1891Promise.prototype.nmcall = // XXX Based on "Redsandro's" proposal1892Promise.prototype.ninvoke = function (name /*...args*/) {1893var nodeArgs = array_slice(arguments, 1);1894var deferred = defer();1895nodeArgs.push(deferred.makeNodeResolver());1896this.dispatch("post", [name, nodeArgs]).fail(deferred.reject);1897return deferred.promise;1898};18991900/**1901* If a function would like to support both Node continuation-passing-style and1902* promise-returning-style, it can end its internal promise chain with1903* `nodeify(nodeback)`, forwarding the optional nodeback argument. If the user1904* elects to use a nodeback, the result will be sent there. If they do not1905* pass a nodeback, they will receive the result promise.1906* @param object a result (or a promise for a result)1907* @param {Function} nodeback a Node.js-style callback1908* @returns either the promise or nothing1909*/1910Q.nodeify = nodeify;1911function nodeify(object, nodeback) {1912return Q(object).nodeify(nodeback);1913}19141915Promise.prototype.nodeify = function (nodeback) {1916if (nodeback) {1917this.then(function (value) {1918Q.nextTick(function () {1919nodeback(null, value);1920});1921}, function (error) {1922Q.nextTick(function () {1923nodeback(error);1924});1925});1926} else {1927return this;1928}1929};19301931// All code before this point will be filtered from stack traces.1932var qEndingLine = captureLine();19331934return Q;19351936});193719381939