forked from kriskowal/q
-
Notifications
You must be signed in to change notification settings - Fork 0
/
q.js
1489 lines (1296 loc) · 42.6 KB
/
q.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// vim:ts=4:sts=4:sw=4:
/*!
*
* Copyright 2009-2013 Kris Kowal under the terms of the MIT
* license found at http://github.com/kriskowal/q/raw/master/LICENSE
*
* With parts by Tyler Close
* Copyright 2007-2009 Tyler Close under the terms of the MIT X license found
* at http://www.opensource.org/licenses/mit-license.html
* Forked at ref_send.js version: 2009-05-11
*
* With parts by Mark Miller
* Copyright (C) 2011 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*global -WeakMap */
"use strict";
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported
// by Q.
var qStartingLine = captureLine();
var qFileName;
var asap = require("asap");
var WeakMap = require("weak-map");
function isObject(value) {
return value === Object(value);
}
// long stack traces
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, promise) {
// If possible, transform the error stack trace by removing Node and Q
// cruft, then concatenating with the stack trace of `promise`. See #57.
if (hasStacks &&
promise.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var p = promise; !!p && handlers.get(p); p = handlers.get(p).became) {
if (p.stack) {
stacks.unshift(p.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n");
var desiredLines = [];
for (var i = 0; i < lines.length; ++i) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
// In IE10 function name can have spaces ("Anonymous function") O_o
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) {
return [attempt1[1], Number(attempt1[2])];
}
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) {
return [attempt2[1], Number(attempt2[2])];
}
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) {
return [attempt3[1], Number(attempt3[2])];
}
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0];
var lineNumber = fileNameAndLineNumber[1];
return fileName === qFileName &&
lineNumber >= qStartingLine &&
lineNumber <= qEndingLine;
}
// discover own file name and line number range for filtering stack
// traces
function captureLine() {
if (!hasStacks) {
return;
}
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) {
return;
}
qFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function deprecate(callback, name, alternative) {
return function () {
if (
typeof console !== "undefined" &&
typeof console.warn === "function"
) {
console.warn(
name + " is deprecated, use " + alternative + " instead.",
new Error("").stack
);
}
return callback.apply(this, arguments);
};
}
// end of long stack traces
var handlers = new WeakMap();
function inspect(promise) {
var handler = handlers.get(promise);
if (!handler || !handler.became) {
return handler;
}
handler = followHandler(handler);
handlers.set(promise, handler);
return handler;
}
function followHandler(handler) {
if (!handler.became) {
return handler;
} else {
handler.became = followHandler(handler.became);
return handler.became;
}
}
var theViciousCycleError = new Error("Can't resolve a promise with itself");
var theViciousCycleRejection = reject(theViciousCycleError);
var theViciousCycleHandler = inspect(theViciousCycleRejection);
var thenables = new WeakMap();
/**
* Coerces a value to a promise. If the value is a promise, pass it through
* unaltered. If the value has a `then` method, it is presumed to be a promise
* but not one of our own, so it is treated as a “thenable” promise and this
* returns a promise that stands for it. Otherwise, this returns a promise that
* has already been fulfilled with the value.
* @param value promise, object with a then method, or a fulfillment value
* @returns {Promise} the same promise as given, or a promise for the given
* value
*/
module.exports = Q;
function Q(value) {
// If the object is already a Promise, return it directly. This enables
// the resolve function to both be used to created references from objects,
// but to tolerably coerce non-promises to promises.
if (isPromise(value)) {
return value;
} else if (isThenable(value)) {
if (!thenables.has(value)) {
thenables.set(value, new Promise(new ThenableHandler(value)));
}
return thenables.get(value);
} else {
return new Promise(new FulfilledHandler(value));
}
}
/**
* Controls whether or not long stack traces will be on
* @type {boolean}
*/
Q.longStackSupport = false;
/**
* Returns a promise that has been rejected with a reason, which should be an
* instance of `Error`.
* @param {Error} error reason for the failure.
* @returns {Promise} rejection
*/
Q.reject = reject;
function reject(error) {
return new Promise(new RejectedHandler(error));
}
/**
* Constructs a {promise, resolve, reject} object.
*
* `resolve` is a callback to invoke with a more resolved value for the
* promise. To fulfill the promise, invoke `resolve` with any value that is
* not a thenable. To reject the promise, invoke `resolve` with a rejected
* thenable, or invoke `reject` with the reason directly. To resolve the
* promise to another thenable, thus putting it in the same state, invoke
* `resolve` with that other thenable.
*
* @returns {{promise, resolve, reject}} a deferred
*/
Q.defer = defer;
function defer() {
var handler = new DeferredHandler();
var promise = new Promise(handler);
var deferred = new Deferred(promise);
if (Q.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
// NOTE: don't try to use `Error.captureStackTrace` or transfer the
// accessor around; that causes memory leaks as per GH-111. Just
// reify the stack trace as a string ASAP.
//
// At the same time, cut off the first line; it's always just
// "[object Promise]\n", as per the `toString`.
promise.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
}
return deferred;
}
// TODO
/**
*/
Q.when = function (value, fulfilled, rejected, ms) {
return Q(value).then(fulfilled, rejected, ms);
};
/**
* Turns an array of promises into a promise for an array. If any of the
* promises gets rejected, the whole array is rejected immediately.
* @param {Array.<Promise>} an array (or promise for an array) of values (or
* promises for values)
* @returns {Promise.<Array>} a promise for an array of the corresponding values
*/
// By Mark Miller
// http://wiki.ecmascript.org/doku.php?id=strawman:concurrency&rev=1308776521#allfulfilled
Q.all = all;
function all(questions) {
// XXX deprecated behavior
if (Q.isPromise(questions)) {
if (
typeof console !== "undefined" &&
typeof console.warn === "function"
) {
console.warn("Q.all no longer directly unwraps a promise. Use Q(array).all()");
}
return Q(questions).all();
}
var countDown = 0;
var deferred = defer();
var answers = Array(questions.length);
var estimates = [];
var estimate = -Infinity;
var setEstimate;
Array.prototype.forEach.call(questions, function (promise, index) {
var handler;
if (
isPromise(promise) &&
(handler = inspect(promise)).state === "fulfilled"
) {
answers[index] = handler.value;
} else {
++countDown;
promise = Q(promise);
promise.then(
function (value) {
answers[index] = value;
if (--countDown === 0) {
deferred.resolve(answers);
}
},
deferred.reject
);
promise.observeEstimate(function (newEstimate) {
var oldEstimate = estimates[index];
estimates[index] = newEstimate;
if (newEstimate > estimate) {
estimate = newEstimate;
} else if (oldEstimate === estimate && newEstimate <= estimate) {
// There is a 1/length chance that we will need to perform
// this O(length) walk, so amortized O(1)
computeEstimate();
}
if (estimates.length === questions.length && estimate !== setEstimate) {
deferred.setEstimate(estimate);
setEstimate = estimate;
}
});
}
});
function computeEstimate() {
estimate = -Infinity;
for (var index = 0; index < estimates.length; index++) {
if (estimates[index] > estimate) {
estimate = estimates[index];
}
}
}
if (countDown === 0) {
deferred.resolve(answers);
}
return deferred.promise;
}
/**
* @see Promise#allSettled
*/
Q.allSettled = allSettled;
function allSettled(questions) {
// XXX deprecated behavior
if (Q.isPromise(questions)) {
if (
typeof console !== "undefined" &&
typeof console.warn === "function"
) {
console.warn("Q.allSettled no longer directly unwraps a promise. Use Q(array).allSettled()");
}
return Q(questions).allSettled();
}
return all(questions.map(function (promise) {
promise = Q(promise);
function regardless() {
return promise.inspect();
}
return promise.then(regardless, regardless);
}));
}
/**
* Returns a promise for the given value (or promised value), some
* milliseconds after it resolved. Passes rejections immediately.
* @param {Any*} promise
* @param {Number} milliseconds
* @returns a promise for the resolution of the given promise after milliseconds
* time has elapsed since the resolution of the given promise.
* If the given promise rejects, that is passed immediately.
*/
Q.delay = function (object, timeout) {
if (timeout === void 0) {
timeout = object;
object = void 0;
}
return Q(object).delay(timeout);
};
/**
* Causes a promise to be rejected if it does not get fulfilled before
* some milliseconds time out.
* @param {Any*} promise
* @param {Number} milliseconds timeout
* @param {String} custom error message (optional)
* @returns a promise for the resolution of the given promise if it is
* fulfilled before the timeout, otherwise rejected.
*/
Q.timeout = function (object, ms, message) {
return Q(object).timeout(ms, message);
};
/**
* Spreads the values of a promised array of arguments into the
* fulfillment callback.
* @param fulfilled callback that receives variadic arguments from the
* promised array
* @param rejected callback that receives the exception if the promise
* is rejected.
* @returns a promise for the return value or thrown exception of
* either callback.
*/
Q.spread = spread;
function spread(value, fulfilled, rejected) {
return Q(value).spread(fulfilled, rejected);
}
/**
* If two promises eventually fulfill to the same value, promises that value,
* but otherwise rejects.
* @param x {Any*}
* @param y {Any*}
* @returns {Any*} a promise for x and y if they are the same, but a rejection
* otherwise.
*
*/
Q.join = function (x, y) {
return Q.spread([x, y], function (x, y) {
if (x === y) {
// TODO: "===" should be Object.is or equiv
return x;
} else {
throw new Error("Can't join: not the same: " + x + " " + y);
}
});
};
/**
* Returns a promise for the first of an array of promises to become fulfilled.
* @param answers {Array} promises to race
* @returns {Promise} the first promise to be fulfilled
*/
Q.race = race;
function race(answerPs) {
return new Promise(function(deferred) {
answerPs.forEach(function(answerP) {
Q(answerP).then(deferred.resolve, deferred.reject);
});
});
}
/**
* Calls the promised function in a future turn.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q["try"] = function (callback) {
return Q(callback).dispatch("post", [void 0, []]);
};
/**
* TODO
*/
Q.fapply = function (callback, args) {
return Q(callback).dispatch("post", [void 0, args]);
};
/**
* TODO
*/
Q.fcall = function (callback /*, ...args*/) {
return Q(callback).dispatch("post", [void 0, Array.prototype.slice.call(arguments, 1)]);
};
/**
* Binds the promised function, transforming return values into a fulfilled
* promise and thrown errors into a rejected one.
* @param object promise or immediate reference for target function
* @param ...args array of application arguments
*/
Q.fbind = function (object /*...args*/) {
var promise = Q(object);
var args = Array.prototype.slice.call(arguments, 1);
return function fbound() {
return promise.dispatch("post", [
void 0,
args.concat(Array.prototype.slice.call(arguments)),
this
]);
};
};
// XXX experimental. This method is a way to denote that a local value is
// serializable and should be immediately dispatched to a remote upon request,
// instead of passing a reference.
Q.passByCopy = function (object) {
//freeze(object);
//passByCopies.set(object, true);
return object;
};
/**
* The async function is a decorator for generator functions, turning
* them into asynchronous generators. Although generators are only
* part of the newest ECMAScript 6 drafts, this code does not cause
* syntax errors in older engines. This code should continue to work
* and will in fact improve over time as the language improves.
*
* ES6 generators are currently part of V8 version 3.19 with the
* `--harmony-generators` runtime flag enabled. This function does not
* support the former, Pythonic generators that were only implemented
* by SpiderMonkey.
*
* Decorates a generator function such that:
* - it may yield promises
* - execution will continue when that promise is fulfilled
* - the value of the yield expression will be the fulfilled value
* - it returns a promise for the return value (when the generator
* stops iterating)
* - the decorated function returns a promise for the return value
* of the generator or the first rejected promise among those
* yielded.
* - if an error is thrown in the generator, it propagates through
* every following yield until it is caught, or until it escapes
* the generator function altogether, and is translated into a
* rejection for the promise returned by the decorated generator.
*/
Q.async = async;
function async(makeGenerator) {
return function () {
// when verb is "send", arg is a value
// when verb is "throw", arg is an exception
function continuer(verb, arg) {
var result;
try {
result = generator[verb](arg);
} catch (exception) {
return reject(exception);
}
if (result.done) {
return result.value;
} else {
return Q(result.value).then(callback, errback);
}
}
var generator = makeGenerator.apply(this, arguments);
var callback = continuer.bind(continuer, "next");
var errback = continuer.bind(continuer, "throw");
return callback();
};
}
/**
* The spawn function is a small wrapper around async that immediately
* calls the generator and also ends the promise chain, so that any
* unhandled errors are thrown instead of forwarded to the error
* handler. This is useful because it's extremely common to run
* generators at the top-level to work with libraries.
*/
Q.spawn = spawn;
function spawn(makeGenerator) {
Q.async(makeGenerator)().done();
}
/**
* The promised function decorator ensures that any promise arguments
* are settled and passed as values (`this` is also settled and passed
* as a value). It will also ensure that the result of a function is
* always a promise.
*
* @example
* var add = Q.promised(function (a, b) {
* return a + b;
* });
* add(Q(a), Q(B));
*
* @param {function} callback The function to decorate
* @returns {function} a function that has been decorated.
*/
Q.promised = promised;
function promised(callback) {
return function () {
return spread([this, all(arguments)], function (self, args) {
return callback.apply(self, args);
});
};
}
// Thus begins the section dedicated to the Promise
/**
* TODO
*/
Q.Promise = Promise;
function Promise(handler) {
if (!(this instanceof Promise)) {
return new Promise(handler);
}
if (typeof handler === "function") {
var setup = handler;
var deferred = defer();
handler = inspect(deferred.promise);
try {
setup(deferred.resolve, deferred.reject, deferred.setEstimate);
} catch (error) {
deferred.reject(error);
}
}
handlers.set(this, handler);
}
/**
* Turns an array of promises into a promise for an array. If any of the
* promises gets rejected, the whole array is rejected immediately.
* @param {Array.<Promise>} an array (or promise for an array) of values (or
* promises for values)
* @returns {Promise.<Array>} a promise for an array of the corresponding values
*/
Promise.all = all;
/**
* Returns a promise for the first of an array of promises to become fulfilled.
* @param answers {Array} promises to race
* @returns {Promise} the first promise to be fulfilled
*/
Promise.race = race;
/**
* Coerces a value to a promise. If the value is a promise, pass it through
* unaltered. If the value has a `then` method, it is presumed to be a promise
* but not one of our own, so it is treated as a “thenable” promise and this
* returns a promise that stands for it. Otherwise, this returns a promise that
* has already been fulfilled with the value.
* @param value promise, object with a then method, or a fulfillment value
* @returns {Promise} the same promise as given, or a promise for the given
* value
*/
Promise.resolve = resolve;
function resolve(value) {
return Q(value);
}
/**
* Returns a promise that has been rejected with a reason, which should be an
* instance of `Error`.
* @param reason value describing the failure
* @returns {Promise} rejection
*/
Promise.reject = reject;
/**
* @returns {boolean} whether the given value is a promise.
*/
Q.isPromise = isPromise;
function isPromise(object) {
return isObject(object) && !!handlers.get(object);
}
/**
* @returns {boolean} whether the given value is an object with a then method.
*/
Q.isThenable = isThenable;
function isThenable(object) {
return isObject(object) && typeof object.then === "function";
}
/**
* Synchronously produces a snapshot of the internal state of the promise. The
* object will have a `state` property. If the `state` is `"pending"`, there
* will be no further information. If the `state` is `"fulfilled"`, there will
* be a `value` property. If the state is `"rejected"` there will be a `reason`
* property. If the promise was constructed from a “thenable” and `then` nor
* any other method has been dispatched on the promise has been called, the
* state will be `"pending"`. The state object will not be updated if the
* state changes and changing it will have no effect on the promise. Every
* call to `inspect` produces a unique object.
* @returns {{state: string, value?, reason?}}
*/
Promise.prototype.inspect = function () {
// the second layer captures only the relevant "state" properties of the
// handler to prevent leaking the capability to access or alter the
// handler.
return inspect(this).inspect();
};
/**
* @returns {boolean} whether the promise is waiting for a result.
*/
Promise.prototype.isPending = function isPending() {
return inspect(this).state === "pending";
};
/**
* @returns {boolean} whether the promise has ended in a result and has a
* fulfillment value.
*/
Promise.prototype.isFulfilled = function isFulfilled() {
return inspect(this).state === "fulfilled";
};
/**
* @returns {boolean} whether the promise has ended poorly and has a reason for
* its rejection.
*/
Promise.prototype.isRejected = function isRejected() {
return inspect(this).state === "rejected";
};
/**
* @returns {string} merely `"[object Promise]"`
*/
Promise.prototype.toString = function () {
return "[object Promise]";
};
/**
* Creates a new promise, waits for this promise to be resolved, and informs
* either the fullfilled or rejected handler of the result. Whatever result
* comes of the fulfilled or rejected handler, a value returned, a promise
* returned, or an error thrown, becomes the resolution for the promise
* returned by `then`.
*
* @param fulfilled
* @param rejected
* @returns {Promise} for the result of `fulfilled` or `rejected`.
*/
Promise.prototype.then = function then(fulfilled, rejected, ms) {
var self = this;
var deferred = defer();
var _fulfilled;
if (typeof fulfilled === "function") {
_fulfilled = function (value) {
try {
deferred.resolve(fulfilled.call(void 0, value));
} catch (error) {
deferred.reject(error);
}
};
} else {
_fulfilled = deferred.resolve;
}
var _rejected;
if (typeof rejected === "function") {
_rejected = function (error) {
try {
deferred.resolve(rejected.call(void 0, error));
} catch (newError) {
deferred.reject(newError);
}
};
} else {
_rejected = deferred.reject;
}
this.done(_fulfilled, _rejected);
if (ms !== void 0) {
var updateEstimate = function () {
deferred.setEstimate(self.getEstimate() + ms);
};
this.observeEstimate(updateEstimate);
updateEstimate();
}
return deferred.promise;
};
/**
* TODO
*/
Promise.prototype.thenResolve = function thenResolve(value) {
value = Q(value);
// Using all is necessary to aggregate the estimated time to completion.
return all([this, value]).then(function () {
return value;
}, null, 0);
};
/**
* TODO
*/
Promise.prototype.thenReject = function thenReject(reason) {
return this.then(function () { throw reason; }, null, 0);
};
/**
* TODO
*/
Promise.prototype.all = function () {
return this.then(Q.all);
};
/**
* Turns an array of promises into a promise for an array of their states (as
* returned by `inspect`) when they have all settled.
* @param {Array[Any*]} values an array (or promise for an array) of values (or
* promises for values)
* @returns {Array[State]} an array of states for the respective values.
*/
Promise.prototype.allSettled = function () {
return this.then(Q.allSettled);
};
/**
* TODO
*/
Promise.prototype["catch"] = function (rejected) {
return this.then(void 0, rejected);
};
/**
* TODO
*/
Promise.prototype["finally"] = function (callback, ms) {
callback = Q(callback);
return this.then(function (value) {
return callback.fcall().then(function () {
return value;
});
}, function (reason) {
// TODO attempt to recycle the rejection with "this".
return callback.fcall().then(function () {
throw reason;
});
}, ms);
};
/**
* Terminates a chain of promises, forcing rejections to be
* thrown as exceptions.
* @param fulfilled
* @param rejected
*/
Promise.prototype.done = function Promise$done(fulfilled, rejected) {
var self = this;
var done = false; // ensure the untrusted promise makes at most a
// single call to one of the callbacks
asap(function () {
var _fulfilled;
if (typeof fulfilled === "function") {
if (Q.onerror) {
_fulfilled = function (value) {
if (done) {
return;
}
done = true;
try {
fulfilled.call(void 0, value);
} catch (error) {
// fallback to rethrow is still necessary because
// _fulfilled is not called in the same event as the
// above guard.
(Q.onerror || rethrow)(error);
}
};
} else {
_fulfilled = function (value) {
if (done) {
return;
}
done = true;
fulfilled.call(void 0, value);
};
}
}
var _rejected;
if (typeof rejected === "function" && Q.onerror) {
_rejected = function (error) {
if (done) {
return;
}
done = true;
makeStackTraceLong(error, self);
try {
rejected.call(void 0, error);
} catch (newError) {
(Q.onerror || rethrow)(newError);
}
};
} else if (typeof rejected === "function") {
_rejected = function (error) {
if (done) {
return;
}
done = true;
makeStackTraceLong(error, self);
rejected.call(void 0, error);
};
} else {
_rejected = Q.onerror || rethrow;
}
if (typeof process === "object" && process.domain) {
_rejected = process.domain.bind(_rejected);
}
inspect(self).dispatch(_fulfilled, "then", [_rejected]);
});
};
function rethrow(error) {
throw error;
}
Promise.prototype.observeEstimate = function (emit) {
this.dispatch("estimate", [emit]);
return this;
};
Promise.prototype.getEstimate = function () {
return inspect(this).estimate;
};
/**
* TODO
*/
Promise.prototype.dispatch = function (op, args) {
var self = this;
var deferred = defer();
asap(function () {
inspect(self).dispatch(deferred.resolve, op, args);
});
return deferred.promise;
};
/**
* TODO
*/
Promise.prototype.get = function (key) {
return this.dispatch("get", [key]);
};
/**
* TODO
*/
Promise.prototype.post = function (name, args, thisp) {
return this.dispatch("post", [name, args, thisp]);
};
/**
* TODO
*/
Promise.prototype.invoke = function (name /*...args*/) {
return this.dispatch("post", [name, Array.prototype.slice.call(arguments, 1)]);
};
/**
* TODO
*/
Promise.prototype.fapply = function (args) {
return this.dispatch("post", [void 0, args]);
};
/**
* TODO
*/
Promise.prototype.fcall = function (/*...args*/) {
return this.dispatch("post", [void 0, Array.prototype.slice.call(arguments)]);
};
/**
* TODO
*/
Promise.prototype.keys = function () {
return this.dispatch("keys", []);
};
/**
* TODO
*/
Promise.prototype.spread = function (fulfilled, rejected, ms) {
return this.all().then(function (array) {
return fulfilled.apply(void 0, array);
}, rejected, ms);
};
/**
* Causes a promise to be rejected if it does not get fulfilled before