vendor: 4,664 bytes, lines 1-159
1if (!Object.entries) { 2 Object.entries = function (obj) { 3 var ownProps = Object.keys(obj), 4 i = ownProps.length, 5 resArray = new Array(i); // preallocate the Array 6 while (i--) 7 resArray[i] = [ownProps[i], obj[ownProps[i]]]; 8 9 return resArray; 10 }; 11} 12 13 14(function (global, factory) { 15 typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : 16 typeof define === 'function' && define.amd ? define(factory) : 17 (global.ES6Promise = factory()); 18}(this, (function () { 19 'use strict'; 20 21 function objectOrFunction(x) { 22 var type = typeof x; 23 return x !== null && (type === 'object' || type === 'function'); 24 } 25 26 function isFunction(x) { 27 return typeof x === 'function'; 28 } 29 30 31 var _isArray = void 0; 32 if (Array.isArray) { 33 _isArray = Array.isArray; 34 } else { 35 _isArray = function (x) { 36 return Object.prototype.toString.call(x) === '[object Array]'; 37 }; 38 } 39 40 var isArray = _isArray; 41 42 var len = 0; 43 var vertxNext = void 0; 44 var customSchedulerFn = void 0; 45 46 var asap = function asap(callback, arg) { 47 queue[len] = callback; 48 queue[len + 1] = arg; 49 len += 2; 50 if (len === 2) { 51 // If len is 2, that means that we need to schedule an async flush. 52 // If additional callbacks are queued before the queue is flushed, they 53 // will be processed by this flush that we are scheduling. 54 if (customSchedulerFn) { 55 customSchedulerFn(flush); 56 } else { 57 scheduleFlush(); 58 } 59 } 60 }; 61 62 function setScheduler(scheduleFn) { 63 customSchedulerFn = scheduleFn; 64 } 65 66 function setAsap(asapFn) { 67 asap = asapFn; 68 } 69 70 var browserWindow = typeof window !== 'undefined' ? window : undefined; 71 var browserGlobal = browserWindow || {}; 72 var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; 73 var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]'; 74 75// test for web worker but not in IE10 76 var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined'; 77 78// node 79 function useNextTick() { 80 // node version 0.10.x displays a deprecation warning when nextTick is used recursively 81 // see https://github.com/cujojs/when/issues/410 for details 82 return function () { 83 return process.nextTick(flush); 84 }; 85 } 86 87// vertx 88 function useVertxTimer() { 89 if (typeof vertxNext !== 'undefined') { 90 return function () { 91 vertxNext(flush); 92 }; 93 } 94 95 return useSetTimeout(); 96 } 97 98 function useMutationObserver() { 99 var iterations = 0; 100 var observer = new BrowserMutationObserver(flush); 101 var node = document.createTextNode(''); 102 observer.observe(node, {characterData: true}); 103 104 return function () { 105 node.data = iterations = ++iterations % 2; 106 }; 107 } 108 109// web worker 110 function useMessageChannel() { 111 var channel = new MessageChannel(); 112 channel.port1.onmessage = flush; 113 return function () { 114 return channel.port2.postMessage(0); 115 }; 116 } 117 118 function useSetTimeout() { 119 // Store setTimeout reference so es6-promise will be unaffected by 120 // other code modifying setTimeout (like sinon.useFakeTimers()) 121 var globalSetTimeout = setTimeout; 122 return function () { 123 return globalSetTimeout(flush, 1); 124 }; 125 } 126 127 var queue = new Array(1000); 128 129 function flush() { 130 for (var i = 0; i < len; i += 2) { 131 var callback = queue[i]; 132 var arg = queue[i + 1]; 133 134 callback(arg); 135 136 queue[i] = undefined; 137 queue[i + 1] = undefined; 138 } 139 140 len = 0; 141 } 142 143 function attemptVertx() { 144 try { 145 var vertx = Function('return this')().require('vertx'); 146 vertxNext = vertx.runOnLoop || vertx.runOnContext; 147 return useVertxTimer(); 148 } catch (e) { 149 return useSetTimeout(); 150 } 151 } 152 153 var scheduleFlush = void 0; 154// Decide what async method to use to triggering processing of queued callbacks: 155 if (isNode) { 156 scheduleFlush = useNextTick(); 157 } else if (BrowserMutationObserver) { 158 scheduleFlush = useMutationObserver(); 159 } else if (isWorker) {
vendor: 5,024 bytes, lines 160-335
160 scheduleFlush = useMessageChannel(); 161 } else if (browserWindow === undefined && typeof require === 'function') { 162 scheduleFlush = attemptVertx(); 163 } else { 164 scheduleFlush = useSetTimeout(); 165 } 166 167 function then(onFulfillment, onRejection) { 168 var parent = this; 169 170 var child = new this.constructor(noop); 171 172 if (child[PROMISE_ID] === undefined) { 173 makePromise(child); 174 } 175 176 var _state = parent._state; 177 178 179 if (_state) { 180 var callback = arguments[_state - 1]; 181 asap(function () { 182 return invokeCallback(_state, child, callback, parent._result); 183 }); 184 } else { 185 subscribe(parent, child, onFulfillment, onRejection); 186 } 187 188 return child; 189 } 190 191 /** 192 `Promise.resolve` returns a promise that will become resolved with the 193 passed `value`. It is shorthand for the following: 194 195 ```javascript 196 let promise = new Promise(function(resolve, reject){ 197resolve(1); 198}); 199 200 promise.then(function(value){ 201// value === 1 202}); 203 ``` 204 205 Instead of writing the above, your code now simply becomes the following: 206 207 ```javascript 208 let promise = Promise.resolve(1); 209 210 promise.then(function(value){ 211// value === 1 212}); 213 ``` 214 215 @method resolve 216 @static 217 @param {Any} value value that the returned promise will be resolved with 218 Useful for tooling. 219 @return {Promise} a promise that will become fulfilled with the given 220 `value` 221 */ 222 function resolve$1(object) { 223 /*jshint validthis:true */ 224 var Constructor = this; 225 226 if (object && typeof object === 'object' && object.constructor === Constructor) { 227 return object; 228 } 229 230 var promise = new Constructor(noop); 231 resolve(promise, object); 232 return promise; 233 } 234 235 var PROMISE_ID = Math.random().toString(36).substring(2); 236 237 function noop() { 238 } 239 240 var PENDING = void 0; 241 var FULFILLED = 1; 242 var REJECTED = 2; 243 244 function selfFulfillment() { 245 return new TypeError("You cannot resolve a promise with itself"); 246 } 247 248 function cannotReturnOwn() { 249 return new TypeError('A promises callback cannot return that same promise.'); 250 } 251 252 function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) { 253 try { 254 then$$1.call(value, fulfillmentHandler, rejectionHandler); 255 } catch (e) { 256 return e; 257 } 258 } 259 260 function handleForeignThenable(promise, thenable, then$$1) { 261 asap(function (promise) { 262 var sealed = false; 263 var error = tryThen(then$$1, thenable, function (value) { 264 if (sealed) { 265 return; 266 } 267 sealed = true; 268 if (thenable !== value) { 269 resolve(promise, value); 270 } else { 271 fulfill(promise, value); 272 } 273 }, function (reason) { 274 if (sealed) { 275 return; 276 } 277 sealed = true; 278 279 reject(promise, reason); 280 }, 'Settle: ' + (promise._label || ' unknown promise')); 281 282 if (!sealed && error) { 283 sealed = true; 284 reject(promise, error); 285 } 286 }, promise); 287 } 288 289 function handleOwnThenable(promise, thenable) { 290 if (thenable._state === FULFILLED) { 291 fulfill(promise, thenable._result); 292 } else if (thenable._state === REJECTED) { 293 reject(promise, thenable._result); 294 } else { 295 subscribe(thenable, undefined, function (value) { 296 return resolve(promise, value); 297 }, function (reason) { 298 return reject(promise, reason); 299 }); 300 } 301 } 302 303 function handleMaybeThenable(promise, maybeThenable, then$$1) { 304 if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) { 305 handleOwnThenable(promise, maybeThenable); 306 } else { 307 if (then$$1 === undefined) { 308 fulfill(promise, maybeThenable); 309 } else if (isFunction(then$$1)) { 310 handleForeignThenable(promise, maybeThenable, then$$1); 311 } else { 312 fulfill(promise, maybeThenable); 313 } 314 } 315 } 316 317 function resolve(promise, value) { 318 if (promise === value) { 319 reject(promise, selfFulfillment()); 320 } else if (objectOrFunction(value)) { 321 var then$$1 = void 0; 322 try { 323 then$$1 = value.then; 324 } catch (error) { 325 reject(promise, error); 326 return; 327 } 328 handleMaybeThenable(promise, value, then$$1); 329 } else { 330 fulfill(promise, value); 331 } 332 } 333 334 function publishRejection(promise) { 335 if (promise._onerror) {
vendor: 9,780 bytes, lines 336-674
336 promise._onerror(promise._result); 337 } 338 339 publish(promise); 340 } 341 342 function fulfill(promise, value) { 343 if (promise._state !== PENDING) { 344 return; 345 } 346 347 promise._result = value; 348 promise._state = FULFILLED; 349 350 if (promise._subscribers.length !== 0) { 351 asap(publish, promise); 352 } 353 } 354 355 function reject(promise, reason) { 356 if (promise._state !== PENDING) { 357 return; 358 } 359 promise._state = REJECTED; 360 promise._result = reason; 361 362 asap(publishRejection, promise); 363 } 364 365 function subscribe(parent, child, onFulfillment, onRejection) { 366 var _subscribers = parent._subscribers; 367 var length = _subscribers.length; 368 369 370 parent._onerror = null; 371 372 _subscribers[length] = child; 373 _subscribers[length + FULFILLED] = onFulfillment; 374 _subscribers[length + REJECTED] = onRejection; 375 376 if (length === 0 && parent._state) { 377 asap(publish, parent); 378 } 379 } 380 381 function publish(promise) { 382 var subscribers = promise._subscribers; 383 var settled = promise._state; 384 385 if (subscribers.length === 0) { 386 return; 387 } 388 389 var child = void 0, 390 callback = void 0, 391 detail = promise._result; 392 393 for (var i = 0; i < subscribers.length; i += 3) { 394 child = subscribers[i]; 395 callback = subscribers[i + settled]; 396 397 if (child) { 398 invokeCallback(settled, child, callback, detail); 399 } else { 400 callback(detail); 401 } 402 } 403 404 promise._subscribers.length = 0; 405 } 406 407 function invokeCallback(settled, promise, callback, detail) { 408 var hasCallback = isFunction(callback), 409 value = void 0, 410 error = void 0, 411 succeeded = true; 412 413 if (hasCallback) { 414 try { 415 value = callback(detail); 416 } catch (e) { 417 succeeded = false; 418 error = e; 419 } 420 421 if (promise === value) { 422 reject(promise, cannotReturnOwn()); 423 return; 424 } 425 } else { 426 value = detail; 427 } 428 429 if (promise._state !== PENDING) { 430 // noop 431 } else if (hasCallback && succeeded) { 432 resolve(promise, value); 433 } else if (succeeded === false) { 434 reject(promise, error); 435 } else if (settled === FULFILLED) { 436 fulfill(promise, value); 437 } else if (settled === REJECTED) { 438 reject(promise, value); 439 } 440 } 441 442 function initializePromise(promise, resolver) { 443 try { 444 resolver(function resolvePromise(value) { 445 resolve(promise, value); 446 }, function rejectPromise(reason) { 447 reject(promise, reason); 448 }); 449 } catch (e) { 450 reject(promise, e); 451 } 452 } 453 454 var id = 0; 455 456 function nextId() { 457 return id++; 458 } 459 460 function makePromise(promise) { 461 promise[PROMISE_ID] = id++; 462 promise._state = undefined; 463 promise._result = undefined; 464 promise._subscribers = []; 465 } 466 467 function validationError() { 468 return new Error('Array Methods must be provided an Array'); 469 } 470 471 var Enumerator = function () { 472 function Enumerator(Constructor, input) { 473 this._instanceConstructor = Constructor; 474 this.promise = new Constructor(noop); 475 476 if (!this.promise[PROMISE_ID]) { 477 makePromise(this.promise); 478 } 479 480 if (isArray(input)) { 481 this.length = input.length; 482 this._remaining = input.length; 483 484 this._result = new Array(this.length); 485 486 if (this.length === 0) { 487 fulfill(this.promise, this._result); 488 } else { 489 this.length = this.length || 0; 490 this._enumerate(input); 491 if (this._remaining === 0) { 492 fulfill(this.promise, this._result); 493 } 494 } 495 } else { 496 reject(this.promise, validationError()); 497 } 498 } 499 500 Enumerator.prototype._enumerate = function _enumerate(input) { 501 for (var i = 0; this._state === PENDING && i < input.length; i++) { 502 this._eachEntry(input[i], i); 503 } 504 }; 505 506 Enumerator.prototype._eachEntry = function _eachEntry(entry, i) { 507 var c = this._instanceConstructor; 508 var resolve$$1 = c.resolve; 509 510 511 if (resolve$$1 === resolve$1) { 512 var _then = void 0; 513 var error = void 0; 514 var didError = false; 515 try { 516 _then = entry.then; 517 } catch (e) { 518 didError = true; 519 error = e; 520 } 521 522 if (_then === then && entry._state !== PENDING) { 523 this._settledAt(entry._state, i, entry._result); 524 } else if (typeof _then !== 'function') { 525 this._remaining--; 526 this._result[i] = entry; 527 } else if (c === Promise$2) { 528 var promise = new c(noop); 529 if (didError) { 530 reject(promise, error); 531 } else { 532 handleMaybeThenable(promise, entry, _then); 533 } 534 this._willSettleAt(promise, i); 535 } else { 536 this._willSettleAt(new c(function (resolve$$1) { 537 return resolve$$1(entry); 538 }), i); 539 } 540 } else { 541 this._willSettleAt(resolve$$1(entry), i); 542 } 543 }; 544 545 Enumerator.prototype._settledAt = function _settledAt(state, i, value) { 546 var promise = this.promise; 547 548 549 if (promise._state === PENDING) { 550 this._remaining--; 551 552 if (state === REJECTED) { 553 reject(promise, value); 554 } else { 555 this._result[i] = value; 556 } 557 } 558 559 if (this._remaining === 0) { 560 fulfill(promise, this._result); 561 } 562 }; 563 564 Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) { 565 var enumerator = this; 566 567 subscribe(promise, undefined, function (value) { 568 return enumerator._settledAt(FULFILLED, i, value); 569 }, function (reason) { 570 return enumerator._settledAt(REJECTED, i, reason); 571 }); 572 }; 573 574 return Enumerator; 575 }(); 576 577 /** 578 `Promise.all` accepts an array of promises, and returns a new promise which 579 is fulfilled with an array of fulfillment values for the passed promises, or 580 rejected with the reason of the first passed promise to be rejected. It casts all 581 elements of the passed iterable to promises as it runs this algorithm. 582 583 Example: 584 585 ```javascript 586 let promise1 = resolve(1); 587 let promise2 = resolve(2); 588 let promise3 = resolve(3); 589 let promises = [ promise1, promise2, promise3 ]; 590 591 Promise.all(promises).then(function(array){ 592// The array here would be [ 1, 2, 3 ]; 593}); 594 ``` 595 596 If any of the `promises` given to `all` are rejected, the first promise 597 that is rejected will be given as an argument to the returned promises's 598 rejection handler. For example: 599 600 Example: 601 602 ```javascript 603 let promise1 = resolve(1); 604 let promise2 = reject(new Error("2")); 605 let promise3 = reject(new Error("3")); 606 let promises = [ promise1, promise2, promise3 ]; 607 608 Promise.all(promises).then(function(array){ 609// Code here never runs because there are rejected promises! 610}, function(error) { 611// error.message === "2" 612}); 613 ``` 614 615 @method all 616 @static 617 @param {Array} entries array of promises 618 @param {String} label optional string for labeling the promise. 619 Useful for tooling. 620 @return {Promise} promise that is fulfilled when all `promises` have been 621 fulfilled, or rejected if any of them become rejected. 622 @static 623 */ 624 function all(entries) { 625 return new Enumerator(this, entries).promise; 626 } 627 628 /** 629 `Promise.race` returns a new promise which is settled in the same way as the 630 first passed promise to settle. 631 632 Example: 633 634 ```javascript 635 let promise1 = new Promise(function(resolve, reject){ 636setTimeout(function(){ 637 resolve('promise 1'); 638}, 200); 639}); 640 641 let promise2 = new Promise(function(resolve, reject){ 642setTimeout(function(){ 643 resolve('promise 2'); 644}, 100); 645}); 646 647 Promise.race([promise1, promise2]).then(function(result){ 648// result === 'promise 2' because it was resolved before promise1 649// was resolved. 650}); 651 ``` 652 653 `Promise.race` is deterministic in that only the state of the first 654 settled promise matters. For example, even if other promises given to the 655 `promises` array argument are resolved, but the first settled promise has 656 become rejected before the other promises became fulfilled, the returned 657 promise will become rejected: 658 659 ```javascript 660 let promise1 = new Promise(function(resolve, reject){ 661setTimeout(function(){ 662 resolve('promise 1'); 663}, 200); 664}); 665 666 let promise2 = new Promise(function(resolve, reject){ 667setTimeout(function(){ 668 reject(new Error('promise 2')); 669}, 100); 670}); 671 672 Promise.race([promise1, promise2]).then(function(result){ 673// Code here never runs 674}, function(reason){
675// reason.message === 'promise 2' because promise 2 became rejected before 676// promise 1 became fulfilled 677}); 678 ``` 679 680 An example real-world use case is implementing timeouts: 681 682 ```javascript 683 Promise.race([ajax('foo.json'), timeout(5000)]) 684 ``` 685 686 @method race 687 @static 688 @param {Array} promises array of promises to observe 689 Useful for tooling. 690 @return {Promise} a promise which settles in the same way as the first passed 691 promise to settle. 692 */ 693 function race(entries) { 694 /*jshint validthis:true */ 695 var Constructor = this; 696 697 if (!isArray(entries)) { 698 return new Constructor(function (_, reject) { 699 return reject(new TypeError('You must pass an array to race.')); 700 }); 701 } else { 702 return new Constructor(function (resolve, reject) { 703 var length = entries.length; 704 for (var i = 0; i < length; i++) { 705 Constructor.resolve(entries[i]).then(resolve, reject); 706 } 707 }); 708 } 709 } 710 711 /** 712 `Promise.reject` returns a promise rejected with the passed `reason`. 713 It is shorthand for the following: 714 715 ```javascript 716 let promise = new Promise(function(resolve, reject){ 717reject(new Error('WHOOPS')); 718}); 719 720 promise.then(function(value){ 721// Code here doesn't run because the promise is rejected! 722}, function(reason){ 723// reason.message === 'WHOOPS' 724}); 725 ``` 726 727 Instead of writing the above, your code now simply becomes the following: 728 729 ```javascript 730 let promise = Promise.reject(new Error('WHOOPS')); 731 732 promise.then(function(value){ 733// Code here doesn't run because the promise is rejected! 734}, function(reason){ 735// reason.message === 'WHOOPS' 736}); 737 ``` 738 739 @method reject 740 @static 741 @param {Any} reason value that the returned promise will be rejected with. 742 Useful for tooling. 743 @return {Promise} a promise rejected with the given `reason`. 744 */ 745 function reject$1(reason) { 746 /*jshint validthis:true */ 747 var Constructor = this; 748 var promise = new Constructor(noop); 749 reject(promise, reason); 750 return promise; 751 } 752 753 function needsResolver() { 754 throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); 755 } 756 757 function needsNew() { 758 throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object c
758onstructor cannot be called as a function."); 759 } 760 761 /** 762 Promise objects represent the eventual result of an asynchronous operation. The 763 primary way of interacting with a promise is through its `then` method, which 764 registers callbacks to receive either a promise's eventual value or the reason 765 why the promise cannot be fulfilled. 766 767 Terminology 768 ----------- 769 770 - `promise` is an object or function with a `then` method whose behavior conforms to this specification. 771 - `thenable` is an object or function that defines a `then` method. 772 - `value` is any legal JavaScript value (including undefined, a thenable, or a promise). 773 - `exception` is a value that is thrown using the throw statement. 774 - `reason` is a value that indicates why a promise was rejected. 775 - `settled` the final resting state of a promise, fulfilled or rejected. 776 777 A promise can be in one of three states: pending, fulfilled, or rejected. 778 779 Promises that are fulfilled have a fulfillment value and are in the fulfilled 780 state. Promises that are rejected have a rejection reason and are in the 781 rejected state. A fulfillment value is never a thenable. 782 783 Promises can also be said to *resolve* a value. If this value is also a 784 promise, then the original promise's settled state will match the value's 785 settled state. So a promise that *resolves* a promise that rejects will 786 itself reject, and a promise that *resolves* a promise that fulfills will 787 itself fulfill. 788 789 790 Basic Usage: 791 ------------ 792 793 ```js 794 let promise = new Promise(function(resolve, reject) { 795// on success 796resolve(value); 797 798// on failure 799reject(reason); 800}); 801 802 promise.then(function(value) { 803// on fulfillment 804}, function(reason) { 805// on rejection 806}); 807 ``` 808 809 Advanced Usage: 810 --------------- 811 812 Promises shine when abstracting away asynchronous interactions such as 813 `XMLHttpRequest`s. 814 815 ```js 816 function getJSON(url) { 817return new Promise(function(resolve, reject){ 818 let xhr = new XMLHttpRequest(); 819 820 xhr.open('GET', url); 821 xhr.onreadystatechange = handler; 822 xhr.responseType = 'json'; 823 xhr.setRequestHeader('Accept', 'application/json'); 824 xhr.send(); 825 826 function handler() { 827 if (this.readyState === this.DONE) { 828 if (this.status === 200) { 829 resolve(this.response); 830 } else { 831 reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); 832 } 833 } 834 }; 835}); 836} 837 838 getJSON('/posts.json').then(function(json) { 839// on fulfillment 840}, function(reason) { 841// on rejection 842}); 843 ``` 844 845 Unlike callbacks, promises are great composable primitives. 846 847 ```js 848 Promise.all([ 849 getJSON('/posts'), 850 getJSON('/comments') 851 ]).then(function(values){ 852values[0] // => postsJSON 853values[1] // => commentsJSON 854 855return values; 856}); 857 ``` 858 859 @class Promise 860 @param {Function} resolver 861 Useful for tooling. 862 @constructor 863 */ 864 865 var Promise$2 = function () { 866 function Promise(resolver) { 867 this[PROMISE_ID] = nextId(); 868 this._result = this._state = undefined; 869 this._subscribers = []; 870 871 if (noop !== resolver) { 872 typeof resolver !== 'function' && needsResolver(); 873 this instanceof Promise ? initializePromise(this, resolver) : needsNew(); 874 } 875 } 876 877 /** 878 The primary way of interacting with a promise is through its `then` method, 879 which registers callbacks to receive either a promise's eventual value or the 880 reason why the promise cannot be fulfilled. 881 ```js 882 findUser().then(function(user){ 883// user is available 884}, function(reason){ 885// user is unavailable, and you are given the reason why 886}); 887 ``` 888 Chaining 889 -------- 890 The return value of `then` is itself a promise. This second, 'downstream' 891 promise is resolved with the return value of the first promise's fulfillment 892 or rejection handler, or rejected if the handler throws an exception. 893 ```js 894 findUser().then(function (user) { 895return user.name; 896}, function (reason) { 897return 'default name'; 898}).then(function (userName) { 899// If `findUser` fulfilled, `userName` will be the user's name, otherwise it 900// will be `'default name'` 901}); 902 findUser().then(function (user) { 903throw new Error('Found user, but still unhappy'); 904}, function (reason) { 905throw new Error('`findUser` rejected and we're unhappy'); 906}).then(function (value) { 907// never reached 908}, function (reason) { 909// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. 910// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. 911}); 912 ``` 913 If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. 914 ```js 915 findUser().then(function (user) { 916throw new PedagogicalException('Upstream error'); 917}).then(function (value) { 918// never reached 919}).then(function (value) { 920// never reached 921}, function (reason) { 922// The `PedgagocialException` is propagated all the way down to here 923}); 924 ``` 925 Assimilation 926 ------------ 927 Sometimes the value you want to propagate to a downstream promise can only be 928 retrieved asynchronously. This can be achieved by returning a promise in the 929 fulfillment or rejection handler. The downstream promise will then be pending 930 until the returned promise is settled. This is called *assimilation*. 931 ```js 932 findUser().then(function (user) { 933return findCommentsByAuthor(user); 934}).then(function (comments) { 935// The user's comments are now available 936}); 937 ``` 938 If the assimliated promise rejects, then the downstream promise will also reject. 939 ```js 940 findUser().then(function (user) { 941return findCommentsByAuthor(user); 942}).then(function (comments) { 943// If `findCommentsByAuthor` fulfills, we'll have the value here 944}, function (reason) { 945// If `findCommentsByAuthor` rejects, we'll have the reason here 946}); 947 ```
948 Simple Example 949 -------------- 950 Synchronous Example 951 ```javascript 952 let result; 953 try { 954result = findResult(); 955// success 956} catch(reason) { 957// failure 958} 959 ``` 960 Errback Example 961 ```js 962 findResult(function(result, err){ 963if (err) { 964 // failure 965} else { 966 // success 967} 968}); 969 ``` 970 Promise Example; 971 ```javascript 972 findResult().then(function(result){ 973// success 974}, function(reason){ 975// failure 976}); 977 ``` 978 Advanced Example 979 -------------- 980 Synchronous Example 981 ```javascript 982 let author, books; 983 try { 984author = findAuthor(); 985books = findBooksByAuthor(author); 986// success 987} catch(reason) { 988// failure 989} 990 ``` 991 Errback Example 992 ```js 993 function foundBooks(books) { 994} 995 function failure(reason) { 996} 997 findAuthor(function(author, err){ 998if (err) { 999 failure(err); 1000 // failure 1001} else { 1002 try { 1003 findBoooksByAuthor(author, function(books, err) { 1004 if (err) { 1005 failure(err); 1006 } else { 1007 try { 1008 foundBooks(books); 1009 } catch(reason) { 1010 failure(reason); 1011 } 1012 } 1013 }); 1014 } catch(error) { 1015 failure(err); 1016 } 1017 // success 1018} 1019}); 1020 ``` 1021 Promise Example; 1022 ```javascript 1023 findAuthor(). 1024 then(findBooksByAuthor). 1025 then(function(books){ 1026 // found books 1027}).catch(function(reason){ 1028// something went wrong 1029}); 1030 ``` 1031 @method then 1032 @param {Function} onFulfilled 1033 @param {Function} onRejected 1034 Useful for tooling. 1035 @return {Promise} 1036 */ 1037 1038 /** 1039 `catch` is simply sugar for `then(undefined, onRejection)` which makes it the same 1040 as the catch block of a try/catch statement. 1041 ```js 1042 function findAuthor(){ 1043throw new Error('couldn't find that author'); 1044} 1045 // synchronous 1046 try { 1047findAuthor(); 1048} catch(reason) { 1049// something went wrong 1050} 1051 // async with promises 1052 findAuthor().catch(function(reason){ 1053// something went wrong 1054}); 1055 ``` 1056 @method catch 1057 @param {Function} onRejection 1058 Useful for tooling. 1059 @return {Promise} 1060 */ 1061 1062 1063 Promise.prototype.catch = function _catch(onRejection) { 1064 return this.then(null, onRejection); 1065 }; 1066 1067 /** 1068 `finally` will be invoked regardless of the promise's fate just as native 1069 try/catch/finally behaves 1070 1071 Synchronous example: 1072 1073 ```js 1074 findAuthor() { 1075 if (Math.random() > 0.5) { 1076 throw new Error(); 1077 } 1078 return new Author(); 1079} 1080 1081 try { 1082 return findAuthor(); // succeed or fail 1083} catch(error) { 1084 return findOtherAuther(); 1085} finally { 1086 // always runs 1087 // doesn't affect the return value 1088} 1089 ``` 1090 1091 Asynchronous example: 1092 1093 ```js 1094 findAuthor().catch(function(reason){ 1095 return findOtherAuther(); 1096}).finally(function(){ 1097 // author was either found, or not 1098}); 1099 ``` 1100 1101 @method finally 1102 @param {Function} callback 1103 @return {Promise} 1104 */ 1105 1106 1107 Promise.prototype.finally = function _finally(callback) { 1108 var promise = this; 1109 var constructor = promise.constructor; 1110 1111 if (isFunction(callback)) { 1112 return promise.then(function (value) { 1113 return constructor.resolve(callback()).then(function () { 1114 return value; 1115 }); 1116 }, function (reason) { 1117 return constructor.resolve(callback()).then(function () { 1118 throw reason; 1119 }); 1120 }); 1121 } 1122 1123 return promise.then(callback, callback); 1124 }; 1125 1126 return Promise; 1127 }(); 1128 1129 Promise$2.prototype.then = then; 1130 Promise$2.all = all; 1131 Promise$2.race = race; 1132 Promise$2.resolve = resolve$1; 1133 Promise$2.reject = reject$1; 1134 Promise$2._setScheduler = setScheduler; 1135 Promise$2._setAsap = setAsap; 1136 Promise$2._asap = asap; 1137 1138 /*global self*/ 1139 function polyfill() { 1140 var local = void 0; 1141 1142 if (typeof global !== 'undefined') { 1143 local = global; 1144 } else if (typeof self !== 'undefined') { 1145 local = self; 1146 } else { 1147 try { 1148 local = Function('return this')(); 1149 } catch (e) { 1150 throw new Error('polyfill failed because global object is unavailable in this environment'); 1151 } 1152 } 1153 1154 var P = local.Promise; 1155 1156 if (P) { 1157 var promiseToString = null; 1158 try { 1159 promiseToString = Object.prototype.toString.call(P.resolve()); 1160 } catch (e) { 1161 // silently ignored 1162 } 1163 1164 if (promiseToString === '[object Promise]' && !P.cast) { 1165 return; 1166 } 1167 } 1168 1169 local.Promise = Promise$2; 1170 } 1171 1172// Strange compat.. 1173 Promise$2.polyfill = polyfill; 1174 Promise$2.Promise = Promise$2; 1175 1176 Promise$2.polyfill(); 1177 1178 return Promise$2; 1179 1180}))); 1181
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.