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