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