Debian Codegraph @

closure-library/third_party/closure/goog/mochikit/async/deferred.js

raw
1 // Copyright 2007 Bob Ippolito. All Rights Reserved.
2 // Modifications Copyright 2009 The Closure Library Authors. All Rights
3 // Reserved.
4
5 /**
6 * @license Portions of this code are from MochiKit, received by
7 * The Closure Authors under the MIT license. All other code is Copyright
8 * 2005-2009 The Closure Authors. All Rights Reserved.
9 */
10
11 /**
12 * @fileoverview Classes for tracking asynchronous operations and handling the
13 * results. The Deferred object here is patterned after the Deferred object in
14 * the Twisted python networking framework.
15 *
16 * See: http://twistedmatrix.com/projects/core/documentation/howto/defer.html
17 *
18 * Based on the Dojo code which in turn is based on the MochiKit code.
19 *
20 * @author [email protected] (Erik Arvidsson)
21 * @author [email protected] (Shawn Brenneman)
22 */
23
24 goog.provide('goog.async.Deferred');
25 goog.provide('goog.async.Deferred.AlreadyCalledError');
26 goog.provide('goog.async.Deferred.CanceledError');
27
28 goog.require('goog.Promise');
29 goog.require('goog.Thenable');
30 goog.require('goog.array');
31 goog.require('goog.asserts');
32 goog.require('goog.debug.Error');
33
34
35
36 /**
37 * A Deferred represents the result of an asynchronous operation. A Deferred
38 * instance has no result when it is created, and is "fired" (given an initial
39 * result) by calling {@code callback} or {@code errback}.
40 *
41 * Once fired, the result is passed through a sequence of callback functions
42 * registered with {@code addCallback} or {@code addErrback}. The functions may
43 * mutate the result before it is passed to the next function in the sequence.
44 *
45 * Callbacks and errbacks may be added at any time, including after the Deferred
46 * has been "fired". If there are no pending actions in the execution sequence
47 * of a fired Deferred, any new callback functions will be called with the last
48 * computed result. Adding a callback function is the only way to access the
49 * result of the Deferred.
50 *
51 * If a Deferred operation is canceled, an optional user-provided cancellation
52 * function is invoked which may perform any special cleanup, followed by firing
53 * the Deferred's errback sequence with a {@code CanceledError}. If the
54 * Deferred has already fired, cancellation is ignored.
55 *
56 * Deferreds may be templated to a specific type they produce using generics
57 * with syntax such as:
58 *
59 * /** @type {goog.async.Deferred<string>} *\
60 * var d = new goog.async.Deferred();
61 * // Compiler can infer that foo is a string.
62 * d.addCallback(function(foo) {...});
63 * d.callback('string'); // Checked to be passed a string
64 *
65 * Since deferreds are often used to produce different values across a chain,
66 * the type information is not propagated across chains, but rather only
67 * associated with specifically cast objects.
68 *
69 * @param {Function=} opt_onCancelFunction A function that will be called if the
70 * Deferred is canceled. If provided, this function runs before the
71 * Deferred is fired with a {@code CanceledError}.
72 * @param {Object=} opt_defaultScope The default object context to call
73 * callbacks and errbacks in.
74 * @constructor
75 * @implements {goog.Thenable<VALUE>}
76 * @template VALUE
77 */
78 goog.async.Deferred = function(opt_onCancelFunction, opt_defaultScope) {
79 /**
80 * Entries in the sequence are arrays containing a callback, an errback, and
81 * an optional scope. The callback or errback in an entry may be null.
82 * @type {!Array<!Array>}
83 * @private
84 */
85 this.sequence_ = [];
86
87 /**
88 * Optional function that will be called if the Deferred is canceled.
89 * @type {Function|undefined}
90 * @private
91 */
92 this.onCancelFunction_ = opt_onCancelFunction;
93
94 /**
95 * The default scope to execute callbacks and errbacks in.
96 * @type {Object}
97 * @private
98 */
99 this.defaultScope_ = opt_defaultScope || null;
100
101 /**
102 * Whether the Deferred has been fired.
103 * @type {boolean}
104 * @private
105 */
106 this.fired_ = false;
107
108 /**
109 * Whether the last result in the execution sequence was an error.
110 * @type {boolean}
111 * @private
112 */
113 this.hadError_ = false;
114
115 /**
116 * The current Deferred result, updated as callbacks and errbacks are
117 * executed.
118 * @type {*}
119 * @private
120 */
121 this.result_ = undefined;
122
123 /**
124 * Whether the Deferred is blocked waiting on another Deferred to fire. If a
125 * callback or errback returns a Deferred as a result, the execution sequence
126 * is blocked until that Deferred result becomes available.
127 * @type {boolean}
128 * @private
129 */
130 this.blocked_ = false;
131
132 /**
133 * Whether this Deferred is blocking execution of another Deferred. If this
134 * instance was returned as a result in another Deferred's execution
135 * sequence,that other Deferred becomes blocked until this instance's
136 * execution sequence completes. No additional callbacks may be added to a
137 * Deferred once it is blocking another instance.
138 * @type {boolean}
139 * @private
140 */
141 this.blocking_ = false;
142
143 /**
144 * Whether the Deferred has been canceled without having a custom cancel
145 * function.
146 * @type {boolean}
147 * @private
148 */
149 this.silentlyCanceled_ = false;
150
151 /**
152 * If an error is thrown during Deferred execution with no errback to catch
153 * it, the error is rethrown after a timeout. Reporting the error after a
154 * timeout allows execution to continue in the calling context (empty when
155 * no error is scheduled).
156 * @type {number}
157 * @private
158 */
159 this.unhandledErrorId_ = 0;
160
161 /**
162 * If this Deferred was created by branch(), this will be the "parent"
163 * Deferred.
164 * @type {goog.async.Deferred}
165 * @private
166 */
167 this.parent_ = null;
168
169 /**
170 * The number of Deferred objects that have been branched off this one. This
171 * will be decremented whenever a branch is fired or canceled.
172 * @type {number}
173 * @private
174 */
175 this.branches_ = 0;
176
177 if (goog.async.Deferred.LONG_STACK_TRACES) {
178 /**
179 * Holds the stack trace at time of deferred creation if the JS engine
180 * provides the Error.captureStackTrace API.
181 * @private {?string}
182 */
183 this.constructorStack_ = null;
184 if (Error.captureStackTrace) {
185 var target = { stack: '' };
186 Error.captureStackTrace(target, goog.async.Deferred);
187 // Check if Error.captureStackTrace worked. It fails in gjstest.
188 if (typeof target.stack == 'string') {
189 // Remove first line and force stringify to prevent memory leak due to
190 // holding on to actual stack frames.
191 this.constructorStack_ = target.stack.replace(/^[^\n]*\n/, '');
192 }
193 }
194 }
195 };
196
197
198 /**
199 * @define {boolean} Whether unhandled errors should always get rethrown to the
200 * global scope. Defaults to the value of goog.DEBUG.
201 */
202 goog.define('goog.async.Deferred.STRICT_ERRORS', false);
203
204
205 /**
206 * @define {boolean} Whether to attempt to make stack traces long. Defaults to
207 * the value of goog.DEBUG.
208 */
209 goog.define('goog.async.Deferred.LONG_STACK_TRACES', false);
210
211
212 /**
213 * Cancels a Deferred that has not yet been fired, or is blocked on another
214 * deferred operation. If this Deferred is waiting for a blocking Deferred to
215 * fire, the blocking Deferred will also be canceled.
216 *
217 * If this Deferred was created by calling branch() on a parent Deferred with
218 * opt_propagateCancel set to true, the parent may also be canceled. If
219 * opt_deepCancel is set, cancel() will be called on the parent (as well as any
220 * other ancestors if the parent is also a branch). If one or more branches were
221 * created with opt_propagateCancel set to true, the parent will be canceled if
222 * cancel() is called on all of those branches.
223 *
224 * @param {boolean=} opt_deepCancel If true, cancels this Deferred's parent even
225 * if cancel() hasn't been called on some of the parent's branches. Has no
226 * effect on a branch without opt_propagateCancel set to true.
227 */
228 goog.async.Deferred.prototype.cancel = function(opt_deepCancel) {
229 if (!this.hasFired()) {
230 if (this.parent_) {
231 // Get rid of the parent reference before potentially running the parent's
232 // canceler function to ensure that this cancellation isn't
233 // double-counted.
234 var parent = this.parent_;
235 delete this.parent_;
236 if (opt_deepCancel) {
237 parent.cancel(opt_deepCancel);
238 } else {
239 parent.branchCancel_();
240 }
241 }
242
243 if (this.onCancelFunction_) {
244 // Call in user-specified scope.
245 this.onCancelFunction_.call(this.defaultScope_, this);
246 } else {
247 this.silentlyCanceled_ = true;
248 }
249 if (!this.hasFired()) {
250 this.errback(new goog.async.Deferred.CanceledError(this));
251 }
252 } else if (this.result_ instanceof goog.async.Deferred) {
253 this.result_.cancel();
254 }
255 };
256
257
258 /**
259 * Handle a single branch being canceled. Once all branches are canceled, this
260 * Deferred will be canceled as well.
261 *
262 * @private
263 */
264 goog.async.Deferred.prototype.branchCancel_ = function() {
265 this.branches_--;
266 if (this.branches_ <= 0) {
267 this.cancel();
268 }
269 };
270
271
272 /**
273 * Called after a blocking Deferred fires. Unblocks this Deferred and resumes
274 * its execution sequence.
275 *
276 * @param {boolean} isSuccess Whether the result is a success or an error.
277 * @param {*} res The result of the blocking Deferred.
278 * @private
279 */
280 goog.async.Deferred.prototype.continue_ = function(isSuccess, res) {
281 this.blocked_ = false;
282 this.updateResult_(isSuccess, res);
283 };
284
285
286 /**
287 * Updates the current result based on the success or failure of the last action
288 * in the execution sequence.
289 *
290 * @param {boolean} isSuccess Whether the new result is a success or an error.
291 * @param {*} res The result.
292 * @private
293 */
294 goog.async.Deferred.prototype.updateResult_ = function(isSuccess, res) {
295 this.fired_ = true;
296 this.result_ = res;
297 this.hadError_ = !isSuccess;
298 this.fire_();
299 };
300
301
302 /**
303 * Verifies that the Deferred has not yet been fired.
304 *
305 * @private
306 * @throws {Error} If this has already been fired.
307 */
308 goog.async.Deferred.prototype.check_ = function() {
309 if (this.hasFired()) {
310 if (!this.silentlyCanceled_) {
311 throw new goog.async.Deferred.AlreadyCalledError(this);
312 }
313 this.silentlyCanceled_ = false;
314 }
315 };
316
317
318 /**
319 * Fire the execution sequence for this Deferred by passing the starting result
320 * to the first registered callback.
321 * @param {VALUE=} opt_result The starting result.
322 */
323 goog.async.Deferred.prototype.callback = function(opt_result) {
324 this.check_();
325 this.assertNotDeferred_(opt_result);
326 this.updateResult_(true /* isSuccess */, opt_result);
327 };
328
329
330 /**
331 * Fire the execution sequence for this Deferred by passing the starting error
332 * result to the first registered errback.
333 * @param {*=} opt_result The starting error.
334 */
335 goog.async.Deferred.prototype.errback = function(opt_result) {
336 this.check_();
337 this.assertNotDeferred_(opt_result);
338 this.makeStackTraceLong_(opt_result);
339 this.updateResult_(false /* isSuccess */, opt_result);
340 };
341
342
343 /**
344 * Attempt to make the error's stack trace be long in that it contains the
345 * stack trace from the point where the deferred was created on top of the
346 * current stack trace to give additional context.
347 * @param {*} error
348 * @private
349 */
350 goog.async.Deferred.prototype.makeStackTraceLong_ = function(error) {
351 if (!goog.async.Deferred.LONG_STACK_TRACES) {
352 return;
353 }
354 if (this.constructorStack_ && goog.isObject(error) && error.stack &&
355 // Stack looks like it was system generated. See
356 // https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
357 (/^[^\n]+(\n [^\n]+)+/).test(error.stack)) {
358 error.stack = error.stack + '\nDEFERRED OPERATION:\n' +
359 this.constructorStack_;
360 }
361 };
362
363
364 /**
365 * Asserts that an object is not a Deferred.
366 * @param {*} obj The object to test.
367 * @throws {Error} Throws an exception if the object is a Deferred.
368 * @private
369 */
370 goog.async.Deferred.prototype.assertNotDeferred_ = function(obj) {
371 goog.asserts.assert(
372 !(obj instanceof goog.async.Deferred),
373 'An execution sequence may not be initiated with a blocking Deferred.');
374 };
375
376
377 /**
378 * Register a callback function to be called with a successful result. If no
379 * value is returned by the callback function, the result value is unchanged. If
380 * a new value is returned, it becomes the Deferred result and will be passed to
381 * the next callback in the execution sequence.
382 *
383 * If the function throws an error, the error becomes the new result and will be
384 * passed to the next errback in the execution chain.
385 *
386 * If the function returns a Deferred, the execution sequence will be blocked
387 * until that Deferred fires. Its result will be passed to the next callback (or
388 * errback if it is an error result) in this Deferred's execution sequence.
389 *
390 * @param {function(this:T,VALUE):?} cb The function to be called with a
391 * successful result.
392 * @param {T=} opt_scope An optional scope to call the callback in.
393 * @return {!goog.async.Deferred} This Deferred.
394 * @template T
395 */
396 goog.async.Deferred.prototype.addCallback = function(cb, opt_scope) {
397 return this.addCallbacks(cb, null, opt_scope);
398 };
399
400
401 /**
402 * Register a callback function to be called with an error result. If no value
403 * is returned by the function, the error result is unchanged. If a new error
404 * value is returned or thrown, that error becomes the Deferred result and will
405 * be passed to the next errback in the execution sequence.
406 *
407 * If the errback function handles the error by returning a non-error value,
408 * that result will be passed to the next normal callback in the sequence.
409 *
410 * If the function returns a Deferred, the execution sequence will be blocked
411 * until that Deferred fires. Its result will be passed to the next callback (or
412 * errback if it is an error result) in this Deferred's execution sequence.
413 *
414 * @param {function(this:T,?):?} eb The function to be called on an
415 * unsuccessful result.
416 * @param {T=} opt_scope An optional scope to call the errback in.
417 * @return {!goog.async.Deferred<VALUE>} This Deferred.
418 * @template T
419 */
420 goog.async.Deferred.prototype.addErrback = function(eb, opt_scope) {
421 return this.addCallbacks(null, eb, opt_scope);
422 };
423
424
425 /**
426 * Registers one function as both a callback and errback.
427 *
428 * @param {function(this:T,?):?} f The function to be called on any result.
429 * @param {T=} opt_scope An optional scope to call the function in.
430 * @return {!goog.async.Deferred} This Deferred.
431 * @template T
432 */
433 goog.async.Deferred.prototype.addBoth = function(f, opt_scope) {
434 return this.addCallbacks(f, f, opt_scope);
435 };
436
437
438 /**
439 * Like addBoth, but propagates uncaught exceptions in the errback.
440 *
441 * @param {function(this:T,?):?} f The function to be called on any result.
442 * @param {T=} opt_scope An optional scope to call the function in.
443 * @return {!goog.async.Deferred<VALUE>} This Deferred.
444 * @template T
445 */
446 goog.async.Deferred.prototype.addFinally = function(f, opt_scope) {
447 return this.addCallbacks(f, function(err) {
448 var result = f.call(/** @type {?} */ (this), err);
449 if (!goog.isDef(result)) {
450 throw err;
451 }
452 return result;
453 }, opt_scope);
454 };
455
456
457 /**
458 * Registers a callback function and an errback function at the same position
459 * in the execution sequence. Only one of these functions will execute,
460 * depending on the error state during the execution sequence.
461 *
462 * NOTE: This is not equivalent to {@code def.addCallback().addErrback()}! If
463 * the callback is invoked, the errback will be skipped, and vice versa.
464 *
465 * @param {?(function(this:T,VALUE):?)} cb The function to be called on a
466 * successful result.
467 * @param {?(function(this:T,?):?)} eb The function to be called on an
468 * unsuccessful result.
469 * @param {T=} opt_scope An optional scope to call the functions in.
470 * @return {!goog.async.Deferred} This Deferred.
471 * @template T
472 */
473 goog.async.Deferred.prototype.addCallbacks = function(cb, eb, opt_scope) {
474 goog.asserts.assert(!this.blocking_, 'Blocking Deferreds can not be re-used');
475 this.sequence_.push([cb, eb, opt_scope]);
476 if (this.hasFired()) {
477 this.fire_();
478 }
479 return this;
480 };
481
482
483 /**
484 * Implements {@see goog.Thenable} for seamless integration with
485 * {@see goog.Promise}.
486 * Deferred results are mutable and may represent multiple values over
487 * their lifetime. Calling {@code then} on a Deferred returns a Promise
488 * with the result of the Deferred at that point in its callback chain.
489 * Note that if the Deferred result is never mutated, and only
490 * {@code then} calls are made, the Deferred will behave like a Promise.
491 *
492 * @override
493 */
494 goog.async.Deferred.prototype.then = function(opt_onFulfilled, opt_onRejected,
495 opt_context) {
496 var resolve, reject;
497 var promise = new goog.Promise(function(res, rej) {
498 // Copying resolvers to outer scope, so that they are available when the
499 // deferred callback fires (which may be synchronous).
500 resolve = res;
501 reject = rej;
502 });
503 this.addCallbacks(resolve, function(reason) {
504 if (reason instanceof goog.async.Deferred.CanceledError) {
505 promise.cancel();
506 } else {
507 reject(reason);
508 }
509 });
510 return promise.then(opt_onFulfilled, opt_onRejected, opt_context);
511 };
512 goog.Thenable.addImplementation(goog.async.Deferred);
513
514
515 /**
516 * Links another Deferred to the end of this Deferred's execution sequence. The
517 * result of this execution sequence will be passed as the starting result for
518 * the chained Deferred, invoking either its first callback or errback.
519 *
520 * @param {!goog.async.Deferred} otherDeferred The Deferred to chain.
521 * @return {!goog.async.Deferred} This Deferred.
522 */
523 goog.async.Deferred.prototype.chainDeferred = function(otherDeferred) {
524 this.addCallbacks(
525 otherDeferred.callback, otherDeferred.errback, otherDeferred);
526 return this;
527 };
528
529
530 /**
531 * Makes this Deferred wait for another Deferred's execution sequence to
532 * complete before continuing.
533 *
534 * This is equivalent to adding a callback that returns {@code otherDeferred},
535 * but doesn't prevent additional callbacks from being added to
536 * {@code otherDeferred}.
537 *
538 * @param {!goog.async.Deferred|!goog.Thenable} otherDeferred The Deferred
539 * to wait for.
540 * @return {!goog.async.Deferred} This Deferred.
541 */
542 goog.async.Deferred.prototype.awaitDeferred = function(otherDeferred) {
543 if (!(otherDeferred instanceof goog.async.Deferred)) {
544 // The Thenable case.
545 return this.addCallback(function() {
546 return otherDeferred;
547 });
548 }
549 return this.addCallback(goog.bind(otherDeferred.branch, otherDeferred));
550 };
551
552
553 /**
554 * Creates a branch off this Deferred's execution sequence, and returns it as a
555 * new Deferred. The branched Deferred's starting result will be shared with the
556 * parent at the point of the branch, even if further callbacks are added to the
557 * parent.
558 *
559 * All branches at the same stage in the execution sequence will receive the
560 * same starting value.
561 *
562 * @param {boolean=} opt_propagateCancel If cancel() is called on every child
563 * branch created with opt_propagateCancel, the parent will be canceled as
564 * well.
565 * @return {!goog.async.Deferred<VALUE>} A Deferred that will be started with
566 * the computed result from this stage in the execution sequence.
567 */
568 goog.async.Deferred.prototype.branch = function(opt_propagateCancel) {
569 var d = new goog.async.Deferred();
570 this.chainDeferred(d);
571 if (opt_propagateCancel) {
572 d.parent_ = this;
573 this.branches_++;
574 }
575 return d;
576 };
577
578
579 /**
580 * @return {boolean} Whether the execution sequence has been started on this
581 * Deferred by invoking {@code callback} or {@code errback}.
582 */
583 goog.async.Deferred.prototype.hasFired = function() {
584 return this.fired_;
585 };
586
587
588 /**
589 * @param {*} res The latest result in the execution sequence.
590 * @return {boolean} Whether the current result is an error that should cause
591 * the next errback to fire. May be overridden by subclasses to handle
592 * special error types.
593 * @protected
594 */
595 goog.async.Deferred.prototype.isError = function(res) {
596 return res instanceof Error;
597 };
598
599
600 /**
601 * @return {boolean} Whether an errback exists in the remaining sequence.
602 * @private
603 */
604 goog.async.Deferred.prototype.hasErrback_ = function() {
605 return goog.array.some(this.sequence_, function(sequenceRow) {
606 // The errback is the second element in the array.
607 return goog.isFunction(sequenceRow[1]);
608 });
609 };
610
611
612 /**
613 * Exhausts the execution sequence while a result is available. The result may
614 * be modified by callbacks or errbacks, and execution will block if the
615 * returned result is an incomplete Deferred.
616 *
617 * @private
618 */
619 goog.async.Deferred.prototype.fire_ = function() {
620 if (this.unhandledErrorId_ && this.hasFired() && this.hasErrback_()) {
621 // It is possible to add errbacks after the Deferred has fired. If a new
622 // errback is added immediately after the Deferred encountered an unhandled
623 // error, but before that error is rethrown, the error is unscheduled.
624 goog.async.Deferred.unscheduleError_(this.unhandledErrorId_);
625 this.unhandledErrorId_ = 0;
626 }
627
628 if (this.parent_) {
629 this.parent_.branches_--;
630 delete this.parent_;
631 }
632
633 var res = this.result_;
634 var unhandledException = false;
635 var isNewlyBlocked = false;
636
637 while (this.sequence_.length && !this.blocked_) {
638 var sequenceEntry = this.sequence_.shift();
639
640 var callback = sequenceEntry[0];
641 var errback = sequenceEntry[1];
642 var scope = sequenceEntry[2];
643
644 var f = this.hadError_ ? errback : callback;
645 if (f) {
646
647 try {
648 var ret = f.call(scope || this.defaultScope_, res);
649
650 // If no result, then use previous result.
651 if (goog.isDef(ret)) {
652 // Bubble up the error as long as the return value hasn't changed.
653 this.hadError_ = this.hadError_ && (ret == res || this.isError(ret));
654 this.result_ = res = ret;
655 }
656
657 if (goog.Thenable.isImplementedBy(res) ||
658 (typeof goog.global['Promise'] === 'function' &&
659 res instanceof goog.global['Promise'])) {
660 isNewlyBlocked = true;
661 this.blocked_ = true;
662 }
663
664 } catch (ex) {
665 res = ex;
666 this.hadError_ = true;
667 this.makeStackTraceLong_(res);
668
669 if (!this.hasErrback_()) {
670 // If an error is thrown with no additional errbacks in the queue,
671 // prepare to rethrow the error.
672 unhandledException = true;
673 }
674 }
675 }
676 }
677
678 this.result_ = res;
679
680 if (isNewlyBlocked) {
681 var onCallback = goog.bind(this.continue_, this, true /* isSuccess */);
682 var onErrback = goog.bind(this.continue_, this, false /* isSuccess */);
683
684 if (res instanceof goog.async.Deferred) {
685 res.addCallbacks(onCallback, onErrback);
686 res.blocking_ = true;
687 } else {
688 res.then(onCallback, onErrback);
689 }
690 } else if (goog.async.Deferred.STRICT_ERRORS && this.isError(res) &&
691 !(res instanceof goog.async.Deferred.CanceledError)) {
692 this.hadError_ = true;
693 unhandledException = true;
694 }
695
696 if (unhandledException) {
697 // Rethrow the unhandled error after a timeout. Execution will continue, but
698 // the error will be seen by global handlers and the user. The throw will
699 // be canceled if another errback is appended before the timeout executes.
700 // The error's original stack trace is preserved where available.
701 this.unhandledErrorId_ = goog.async.Deferred.scheduleError_(res);
702 }
703 };
704
705
706 /**
707 * Creates a Deferred that has an initial result.
708 *
709 * @param {*=} opt_result The result.
710 * @return {!goog.async.Deferred} The new Deferred.
711 */
712 goog.async.Deferred.succeed = function(opt_result) {
713 var d = new goog.async.Deferred();
714 d.callback(opt_result);
715 return d;
716 };
717
718
719 /**
720 * Creates a Deferred that fires when the given promise resolves.
721 * Use only during migration to Promises.
722 *
723 * @param {!goog.Promise<T>} promise
724 * @return {!goog.async.Deferred<T>} The new Deferred.
725 * @template T
726 */
727 goog.async.Deferred.fromPromise = function(promise) {
728 var d = new goog.async.Deferred();
729 d.callback();
730 d.addCallback(function() {
731 return promise;
732 });
733 return d;
734 };
735
736
737 /**
738 * Creates a Deferred that has an initial error result.
739 *
740 * @param {*} res The error result.
741 * @return {!goog.async.Deferred} The new Deferred.
742 */
743 goog.async.Deferred.fail = function(res) {
744 var d = new goog.async.Deferred();
745 d.errback(res);
746 return d;
747 };
748
749
750 /**
751 * Creates a Deferred that has already been canceled.
752 *
753 * @return {!goog.async.Deferred} The new Deferred.
754 */
755 goog.async.Deferred.canceled = function() {
756 var d = new goog.async.Deferred();
757 d.cancel();
758 return d;
759 };
760
761
762 /**
763 * Normalizes values that may or may not be Deferreds.
764 *
765 * If the input value is a Deferred, the Deferred is branched (so the original
766 * execution sequence is not modified) and the input callback added to the new
767 * branch. The branch is returned to the caller.
768 *
769 * If the input value is not a Deferred, the callback will be executed
770 * immediately and an already firing Deferred will be returned to the caller.
771 *
772 * In the following (contrived) example, if <code>isImmediate</code> is true
773 * then 3 is alerted immediately, otherwise 6 is alerted after a 2-second delay.
774 *
775 * <pre>
776 * var value;
777 * if (isImmediate) {
778 * value = 3;
779 * } else {
780 * value = new goog.async.Deferred();
781 * setTimeout(function() { value.callback(6); }, 2000);
782 * }
783 *
784 * var d = goog.async.Deferred.when(value, alert);
785 * </pre>
786 *
787 * @param {*} value Deferred or normal value to pass to the callback.
788 * @param {function(this:T, ?):?} callback The callback to execute.
789 * @param {T=} opt_scope An optional scope to call the callback in.
790 * @return {!goog.async.Deferred} A new Deferred that will call the input
791 * callback with the input value.
792 * @template T
793 */
794 goog.async.Deferred.when = function(value, callback, opt_scope) {
795 if (value instanceof goog.async.Deferred) {
796 return value.branch(true).addCallback(callback, opt_scope);
797 } else {
798 return goog.async.Deferred.succeed(value).addCallback(callback, opt_scope);
799 }
800 };
801
802
803
804 /**
805 * An error sub class that is used when a Deferred has already been called.
806 * @param {!goog.async.Deferred} deferred The Deferred.
807 *
808 * @constructor
809 * @extends {goog.debug.Error}
810 */
811 goog.async.Deferred.AlreadyCalledError = function(deferred) {
812 goog.debug.Error.call(this);
813
814 /**
815 * The Deferred that raised this error.
816 * @type {goog.async.Deferred}
817 */
818 this.deferred = deferred;
819 };
820 goog.inherits(goog.async.Deferred.AlreadyCalledError, goog.debug.Error);
821
822
823 /** @override */
824 goog.async.Deferred.AlreadyCalledError.prototype.message =
825 'Deferred has already fired';
826
827
828 /** @override */
829 goog.async.Deferred.AlreadyCalledError.prototype.name = 'AlreadyCalledError';
830
831
832
833 /**
834 * An error sub class that is used when a Deferred is canceled.
835 *
836 * @param {!goog.async.Deferred} deferred The Deferred object.
837 * @constructor
838 * @extends {goog.debug.Error}
839 */
840 goog.async.Deferred.CanceledError = function(deferred) {
841 goog.debug.Error.call(this);
842
843 /**
844 * The Deferred that raised this error.
845 * @type {goog.async.Deferred}
846 */
847 this.deferred = deferred;
848 };
849 goog.inherits(goog.async.Deferred.CanceledError, goog.debug.Error);
850
851
852 /** @override */
853 goog.async.Deferred.CanceledError.prototype.message = 'Deferred was canceled';
854
855
856 /** @override */
857 goog.async.Deferred.CanceledError.prototype.name = 'CanceledError';
858
859
860
861 /**
862 * Wrapper around errors that are scheduled to be thrown by failing deferreds
863 * after a timeout.
864 *
865 * @param {*} error Error from a failing deferred.
866 * @constructor
867 * @final
868 * @private
869 * @struct
870 */
871 goog.async.Deferred.Error_ = function(error) {
872 /** @const @private {number} */
873 this.id_ = goog.global.setTimeout(goog.bind(this.throwError, this), 0);
874
875 /** @const @private {*} */
876 this.error_ = error;
877 };
878
879
880 /**
881 * Actually throws the error and removes it from the list of pending
882 * deferred errors.
883 */
884 goog.async.Deferred.Error_.prototype.throwError = function() {
885 goog.asserts.assert(goog.async.Deferred.errorMap_[this.id_],
886 'Cannot throw an error that is not scheduled.');
887 delete goog.async.Deferred.errorMap_[this.id_];
888 throw this.error_;
889 };
890
891
892 /**
893 * Resets the error throw timer.
894 */
895 goog.async.Deferred.Error_.prototype.resetTimer = function() {
896 goog.global.clearTimeout(this.id_);
897 };
898
899
900 /**
901 * Map of unhandled errors scheduled to be rethrown in a future timestep.
902 * @private {!Object<(number|string), goog.async.Deferred.Error_>}
903 */
904 goog.async.Deferred.errorMap_ = {};
905
906
907 /**
908 * Schedules an error to be thrown after a delay.
909 * @param {*} error Error from a failing deferred.
910 * @return {number} Id of the error.
911 * @private
912 */
913 goog.async.Deferred.scheduleError_ = function(error) {
914 var deferredError = new goog.async.Deferred.Error_(error);
915 goog.async.Deferred.errorMap_[deferredError.id_] = deferredError;
916 return deferredError.id_;
917 };
918
919
920 /**
921 * Unschedules an error from being thrown.
922 * @param {number} id Id of the deferred error to unschedule.
923 * @private
924 */
925 goog.async.Deferred.unscheduleError_ = function(id) {
926 var error = goog.async.Deferred.errorMap_[id];
927 if (error) {
928 error.resetTimer();
929 delete goog.async.Deferred.errorMap_[id];
930 }
931 };
932
933
934 /**
935 * Asserts that there are no pending deferred errors. If there are any
936 * scheduled errors, one will be thrown immediately to make this function fail.
937 */
938 goog.async.Deferred.assertNoErrors = function() {
939 var map = goog.async.Deferred.errorMap_;
940 for (var key in map) {
941 var error = map[key];
942 error.resetTimer();
943 error.throwError();
944 }
945 };