Last active
August 18, 2018 12:07
-
-
Save eventualbuddha/f64c1f36122f12ebf467 to your computer and use it in GitHub Desktop.
es6-promise as a gist
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
objectOrFunction, | |
isFunction | |
} from './utils'; | |
import asap from './asap'; | |
function noop() {} | |
var PENDING = void 0; | |
var FULFILLED = 1; | |
var REJECTED = 2; | |
var GET_THEN_ERROR = new ErrorObject(); | |
function selfFullfillment() { | |
return new TypeError("You cannot resolve a promise with itself"); | |
} | |
function cannotReturnOwn() { | |
return new TypeError('A promises callback cannot return that same promise.') | |
} | |
function getThen(promise) { | |
try { | |
return promise.then; | |
} catch(error) { | |
GET_THEN_ERROR.error = error; | |
return GET_THEN_ERROR; | |
} | |
} | |
function tryThen(then, value, fulfillmentHandler, rejectionHandler) { | |
try { | |
then.call(value, fulfillmentHandler, rejectionHandler); | |
} catch(e) { | |
return e; | |
} | |
} | |
function handleForeignThenable(promise, thenable, then) { | |
asap(function(promise) { | |
var sealed = false; | |
var error = tryThen(then, thenable, function(value) { | |
if (sealed) { return; } | |
sealed = true; | |
if (thenable !== value) { | |
resolve(promise, value); | |
} else { | |
fulfill(promise, value); | |
} | |
}, function(reason) { | |
if (sealed) { return; } | |
sealed = true; | |
reject(promise, reason); | |
}, 'Settle: ' + (promise._label || ' unknown promise')); | |
if (!sealed && error) { | |
sealed = true; | |
reject(promise, error); | |
} | |
}, promise); | |
} | |
function handleOwnThenable(promise, thenable) { | |
if (thenable._state === FULFILLED) { | |
fulfill(promise, thenable._result); | |
} else if (promise._state === REJECTED) { | |
reject(promise, thenable._result); | |
} else { | |
subscribe(thenable, undefined, function(value) { | |
resolve(promise, value); | |
}, function(reason) { | |
reject(promise, reason); | |
}); | |
} | |
} | |
function handleMaybeThenable(promise, maybeThenable) { | |
if (maybeThenable.constructor === promise.constructor) { | |
handleOwnThenable(promise, maybeThenable); | |
} else { | |
var then = getThen(maybeThenable); | |
if (then === GET_THEN_ERROR) { | |
reject(promise, GET_THEN_ERROR.error); | |
} else if (then === undefined) { | |
fulfill(promise, maybeThenable); | |
} else if (isFunction(then)) { | |
handleForeignThenable(promise, maybeThenable, then); | |
} else { | |
fulfill(promise, maybeThenable); | |
} | |
} | |
} | |
function resolve(promise, value) { | |
if (promise === value) { | |
reject(promise, selfFullfillment()); | |
} else if (objectOrFunction(value)) { | |
handleMaybeThenable(promise, value); | |
} else { | |
fulfill(promise, value); | |
} | |
} | |
function publishRejection(promise) { | |
if (promise._onerror) { | |
promise._onerror(promise._result); | |
} | |
publish(promise); | |
} | |
function fulfill(promise, value) { | |
if (promise._state !== PENDING) { return; } | |
promise._result = value; | |
promise._state = FULFILLED; | |
if (promise._subscribers.length === 0) { | |
} else { | |
asap(publish, promise); | |
} | |
} | |
function reject(promise, reason) { | |
if (promise._state !== PENDING) { return; } | |
promise._state = REJECTED; | |
promise._result = reason; | |
asap(publishRejection, promise); | |
} | |
function subscribe(parent, child, onFulfillment, onRejection) { | |
var subscribers = parent._subscribers; | |
var length = subscribers.length; | |
parent._onerror = null; | |
subscribers[length] = child; | |
subscribers[length + FULFILLED] = onFulfillment; | |
subscribers[length + REJECTED] = onRejection; | |
if (length === 0 && parent._state) { | |
asap(publish, parent); | |
} | |
} | |
function publish(promise) { | |
var subscribers = promise._subscribers; | |
var settled = promise._state; | |
if (subscribers.length === 0) { return; } | |
var child, callback, detail = promise._result; | |
for (var i = 0; i < subscribers.length; i += 3) { | |
child = subscribers[i]; | |
callback = subscribers[i + settled]; | |
if (child) { | |
invokeCallback(settled, child, callback, detail); | |
} else { | |
callback(detail); | |
} | |
} | |
promise._subscribers.length = 0; | |
} | |
function ErrorObject() { | |
this.error = null; | |
} | |
var TRY_CATCH_ERROR = new ErrorObject(); | |
function tryCatch(callback, detail) { | |
try { | |
return callback(detail); | |
} catch(e) { | |
TRY_CATCH_ERROR.error = e; | |
return TRY_CATCH_ERROR; | |
} | |
} | |
function invokeCallback(settled, promise, callback, detail) { | |
var hasCallback = isFunction(callback), | |
value, error, succeeded, failed; | |
if (hasCallback) { | |
value = tryCatch(callback, detail); | |
if (value === TRY_CATCH_ERROR) { | |
failed = true; | |
error = value.error; | |
value = null; | |
} else { | |
succeeded = true; | |
} | |
if (promise === value) { | |
reject(promise, cannotReturnOwn()); | |
return; | |
} | |
} else { | |
value = detail; | |
succeeded = true; | |
} | |
if (promise._state !== PENDING) { | |
// noop | |
} else if (hasCallback && succeeded) { | |
resolve(promise, value); | |
} else if (failed) { | |
reject(promise, error); | |
} else if (settled === FULFILLED) { | |
fulfill(promise, value); | |
} else if (settled === REJECTED) { | |
reject(promise, value); | |
} | |
} | |
function initializePromise(promise, resolver) { | |
try { | |
resolver(function resolvePromise(value){ | |
resolve(promise, value); | |
}, function rejectPromise(reason) { | |
reject(promise, reason); | |
}); | |
} catch(e) { | |
reject(promise, e); | |
} | |
} | |
export { | |
noop, | |
resolve, | |
reject, | |
fulfill, | |
subscribe, | |
publish, | |
publishRejection, | |
initializePromise, | |
invokeCallback, | |
FULFILLED, | |
REJECTED, | |
PENDING | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var len = 0; | |
export default function asap(callback, arg) { | |
queue[len] = callback; | |
queue[len + 1] = arg; | |
len += 2; | |
if (len === 2) { | |
// If len is 1, that means that we need to schedule an async flush. | |
// If additional callbacks are queued before the queue is flushed, they | |
// will be processed by this flush that we are scheduling. | |
scheduleFlush(); | |
} | |
} | |
var browserGlobal = (typeof window !== 'undefined') ? window : {}; | |
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver; | |
// test for web worker but not in IE10 | |
var isWorker = typeof Uint8ClampedArray !== 'undefined' && | |
typeof importScripts !== 'undefined' && | |
typeof MessageChannel !== 'undefined'; | |
// node | |
function useNextTick() { | |
return function() { | |
process.nextTick(flush); | |
}; | |
} | |
function useMutationObserver() { | |
var iterations = 0; | |
var observer = new BrowserMutationObserver(flush); | |
var node = document.createTextNode(''); | |
observer.observe(node, { characterData: true }); | |
return function() { | |
node.data = (iterations = ++iterations % 2); | |
}; | |
} | |
// web worker | |
function useMessageChannel() { | |
var channel = new MessageChannel(); | |
channel.port1.onmessage = flush; | |
return function () { | |
channel.port2.postMessage(0); | |
}; | |
} | |
function useSetTimeout() { | |
return function() { | |
setTimeout(flush, 1); | |
}; | |
} | |
var queue = new Array(1000); | |
function flush() { | |
for (var i = 0; i < len; i+=2) { | |
var callback = queue[i]; | |
var arg = queue[i+1]; | |
callback(arg); | |
queue[i] = undefined; | |
queue[i+1] = undefined; | |
} | |
len = 0; | |
} | |
var scheduleFlush; | |
// Decide what async method to use to triggering processing of queued callbacks: | |
if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') { | |
scheduleFlush = useNextTick(); | |
} else if (BrowserMutationObserver) { | |
scheduleFlush = useMutationObserver(); | |
} else if (isWorker) { | |
scheduleFlush = useMessageChannel(); | |
} else { | |
scheduleFlush = useSetTimeout(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
isArray, | |
isMaybeThenable | |
} from './utils'; | |
import { | |
noop, | |
reject, | |
fulfill, | |
subscribe, | |
FULFILLED, | |
REJECTED, | |
PENDING | |
} from './-internal'; | |
export function makeSettledResult(state, position, value) { | |
if (state === FULFILLED) { | |
return { | |
state: 'fulfilled', | |
value: value | |
}; | |
} else { | |
return { | |
state: 'rejected', | |
reason: value | |
}; | |
} | |
} | |
function Enumerator(Constructor, input, abortOnReject, label) { | |
this._instanceConstructor = Constructor; | |
this.promise = new Constructor(noop, label); | |
this._abortOnReject = abortOnReject; | |
if (this._validateInput(input)) { | |
this._input = input; | |
this.length = input.length; | |
this._remaining = input.length; | |
this._init(); | |
if (this.length === 0) { | |
fulfill(this.promise, this._result); | |
} else { | |
this.length = this.length || 0; | |
this._enumerate(); | |
if (this._remaining === 0) { | |
fulfill(this.promise, this._result); | |
} | |
} | |
} else { | |
reject(this.promise, this._validationError()); | |
} | |
} | |
Enumerator.prototype._validateInput = function(input) { | |
return isArray(input); | |
}; | |
Enumerator.prototype._validationError = function() { | |
return new Error('Array Methods must be provided an Array'); | |
}; | |
Enumerator.prototype._init = function() { | |
this._result = new Array(this.length); | |
}; | |
export default Enumerator; | |
Enumerator.prototype._enumerate = function() { | |
var length = this.length; | |
var promise = this.promise; | |
var input = this._input; | |
for (var i = 0; promise._state === PENDING && i < length; i++) { | |
this._eachEntry(input[i], i); | |
} | |
}; | |
Enumerator.prototype._eachEntry = function(entry, i) { | |
var c = this._instanceConstructor; | |
if (isMaybeThenable(entry)) { | |
if (entry.constructor === c && entry._state !== PENDING) { | |
entry._onerror = null; | |
this._settledAt(entry._state, i, entry._result); | |
} else { | |
this._willSettleAt(c.resolve(entry), i); | |
} | |
} else { | |
this._remaining--; | |
this._result[i] = this._makeResult(FULFILLED, i, entry); | |
} | |
}; | |
Enumerator.prototype._settledAt = function(state, i, value) { | |
var promise = this.promise; | |
if (promise._state === PENDING) { | |
this._remaining--; | |
if (this._abortOnReject && state === REJECTED) { | |
reject(promise, value); | |
} else { | |
this._result[i] = this._makeResult(state, i, value); | |
} | |
} | |
if (this._remaining === 0) { | |
fulfill(promise, this._result); | |
} | |
}; | |
Enumerator.prototype._makeResult = function(state, i, value) { | |
return value; | |
}; | |
Enumerator.prototype._willSettleAt = function(promise, i) { | |
var enumerator = this; | |
subscribe(promise, undefined, function(value) { | |
enumerator._settledAt(FULFILLED, i, value); | |
}, function(reason) { | |
enumerator._settledAt(REJECTED, i, reason); | |
}); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Promise from './promise'; | |
import polyfill from './polyfill'; | |
var ES6Promise = { | |
Promise: Promise, | |
polyfill: polyfill | |
}; | |
/* global define:true module:true window: true */ | |
if (typeof define === 'function' && define['amd']) { | |
define(function() { return ES6Promise; }); | |
} else if (typeof module !== 'undefined' && module['exports']) { | |
module['exports'] = ES6Promise; | |
} else if (typeof this !== 'undefined') { | |
this['ES6Promise'] = ES6Promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/*global self*/ | |
import { default as RSVPPromise } from "./promise"; | |
import { isFunction } from "./utils"; | |
export default function polyfill() { | |
var local; | |
if (typeof global !== 'undefined') { | |
local = global; | |
} else if (typeof window !== 'undefined' && window.document) { | |
local = window; | |
} else { | |
local = self; | |
} | |
var es6PromiseSupport = | |
"Promise" in local && | |
// Some of these methods are missing from | |
// Firefox/Chrome experimental implementations | |
"resolve" in local.Promise && | |
"reject" in local.Promise && | |
"all" in local.Promise && | |
"race" in local.Promise && | |
// Older version of the spec had a resolver object | |
// as the arg rather than a function | |
(function() { | |
var resolve; | |
new local.Promise(function(r) { resolve = r; }); | |
return isFunction(resolve); | |
}()); | |
if (!es6PromiseSupport) { | |
local.Promise = RSVPPromise; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Enumerator from '../enumerator'; | |
/** | |
`Promise.all` accepts an array of promises, and returns a new promise which | |
is fulfilled with an array of fulfillment values for the passed promises, or | |
rejected with the reason of the first passed promise to be rejected. It casts all | |
elements of the passed iterable to promises as it runs this algorithm. | |
Example: | |
```javascript | |
var promise1 = resolve(1); | |
var promise2 = resolve(2); | |
var promise3 = resolve(3); | |
var promises = [ promise1, promise2, promise3 ]; | |
Promise.all(promises).then(function(array){ | |
// The array here would be [ 1, 2, 3 ]; | |
}); | |
``` | |
If any of the `promises` given to `all` are rejected, the first promise | |
that is rejected will be given as an argument to the returned promises's | |
rejection handler. For example: | |
Example: | |
```javascript | |
var promise1 = resolve(1); | |
var promise2 = reject(new Error("2")); | |
var promise3 = reject(new Error("3")); | |
var promises = [ promise1, promise2, promise3 ]; | |
Promise.all(promises).then(function(array){ | |
// Code here never runs because there are rejected promises! | |
}, function(error) { | |
// error.message === "2" | |
}); | |
``` | |
@method all | |
@static | |
@param {Array} entries array of promises | |
@param {String} label optional string for labeling the promise. | |
Useful for tooling. | |
@return {Promise} promise that is fulfilled when all `promises` have been | |
fulfilled, or rejected if any of them become rejected. | |
@static | |
*/ | |
export default function all(entries, label) { | |
return new Enumerator(this, entries, true /* abort on reject */, label).promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
isArray | |
} from "../utils"; | |
import { | |
noop, | |
resolve, | |
reject, | |
subscribe, | |
PENDING | |
} from '../-internal'; | |
/** | |
`Promise.race` returns a new promise which is settled in the same way as the | |
first passed promise to settle. | |
Example: | |
```javascript | |
var promise1 = new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve('promise 1'); | |
}, 200); | |
}); | |
var promise2 = new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve('promise 2'); | |
}, 100); | |
}); | |
Promise.race([promise1, promise2]).then(function(result){ | |
// result === 'promise 2' because it was resolved before promise1 | |
// was resolved. | |
}); | |
``` | |
`Promise.race` is deterministic in that only the state of the first | |
settled promise matters. For example, even if other promises given to the | |
`promises` array argument are resolved, but the first settled promise has | |
become rejected before the other promises became fulfilled, the returned | |
promise will become rejected: | |
```javascript | |
var promise1 = new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
resolve('promise 1'); | |
}, 200); | |
}); | |
var promise2 = new Promise(function(resolve, reject){ | |
setTimeout(function(){ | |
reject(new Error('promise 2')); | |
}, 100); | |
}); | |
Promise.race([promise1, promise2]).then(function(result){ | |
// Code here never runs | |
}, function(reason){ | |
// reason.message === 'promise 2' because promise 2 became rejected before | |
// promise 1 became fulfilled | |
}); | |
``` | |
An example real-world use case is implementing timeouts: | |
```javascript | |
Promise.race([ajax('foo.json'), timeout(5000)]) | |
``` | |
@method race | |
@static | |
@param {Array} promises array of promises to observe | |
@param {String} label optional string for describing the promise returned. | |
Useful for tooling. | |
@return {Promise} a promise which settles in the same way as the first passed | |
promise to settle. | |
*/ | |
export default function race(entries, label) { | |
/*jshint validthis:true */ | |
var Constructor = this; | |
var promise = new Constructor(noop, label); | |
if (!isArray(entries)) { | |
reject(promise, new TypeError('You must pass an array to race.')); | |
return promise; | |
} | |
var length = entries.length; | |
function onFulfillment(value) { | |
resolve(promise, value); | |
} | |
function onRejection(reason) { | |
reject(promise, reason); | |
} | |
for (var i = 0; promise._state === PENDING && i < length; i++) { | |
subscribe(Constructor.resolve(entries[i]), undefined, onFulfillment, onRejection); | |
} | |
return promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
noop, | |
reject as _reject | |
} from '../-internal'; | |
/** | |
`Promise.reject` returns a promise rejected with the passed `reason`. | |
It is shorthand for the following: | |
```javascript | |
var promise = new Promise(function(resolve, reject){ | |
reject(new Error('WHOOPS')); | |
}); | |
promise.then(function(value){ | |
// Code here doesn't run because the promise is rejected! | |
}, function(reason){ | |
// reason.message === 'WHOOPS' | |
}); | |
``` | |
Instead of writing the above, your code now simply becomes the following: | |
```javascript | |
var promise = Promise.reject(new Error('WHOOPS')); | |
promise.then(function(value){ | |
// Code here doesn't run because the promise is rejected! | |
}, function(reason){ | |
// reason.message === 'WHOOPS' | |
}); | |
``` | |
@method reject | |
@static | |
@param {Any} reason value that the returned promise will be rejected with. | |
@param {String} label optional string for identifying the returned promise. | |
Useful for tooling. | |
@return {Promise} a promise rejected with the given `reason`. | |
*/ | |
export default function reject(reason, label) { | |
/*jshint validthis:true */ | |
var Constructor = this; | |
var promise = new Constructor(noop, label); | |
_reject(promise, reason); | |
return promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
noop, | |
resolve as _resolve | |
} from '../-internal'; | |
/** | |
`Promise.resolve` returns a promise that will become resolved with the | |
passed `value`. It is shorthand for the following: | |
```javascript | |
var promise = new Promise(function(resolve, reject){ | |
resolve(1); | |
}); | |
promise.then(function(value){ | |
// value === 1 | |
}); | |
``` | |
Instead of writing the above, your code now simply becomes the following: | |
```javascript | |
var promise = Promise.resolve(1); | |
promise.then(function(value){ | |
// value === 1 | |
}); | |
``` | |
@method resolve | |
@static | |
@param {Any} value value that the returned promise will be resolved with | |
@param {String} label optional string for identifying the returned promise. | |
Useful for tooling. | |
@return {Promise} a promise that will become fulfilled with the given | |
`value` | |
*/ | |
export default function resolve(object, label) { | |
/*jshint validthis:true */ | |
var Constructor = this; | |
if (object && typeof object === 'object' && object.constructor === Constructor) { | |
return object; | |
} | |
var promise = new Constructor(noop, label); | |
_resolve(promise, object); | |
return promise; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
isFunction, | |
now | |
} from './utils'; | |
import { | |
noop, | |
subscribe, | |
initializePromise, | |
invokeCallback, | |
FULFILLED, | |
REJECTED | |
} from './-internal'; | |
import asap from './asap'; | |
import all from './promise/all'; | |
import race from './promise/race'; | |
import Resolve from './promise/resolve'; | |
import Reject from './promise/reject'; | |
var counter = 0; | |
function needsResolver() { | |
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor'); | |
} | |
function needsNew() { | |
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function."); | |
} | |
export default Promise; | |
/** | |
Promise objects represent the eventual result of an asynchronous operation. The | |
primary way of interacting with a promise is through its `then` method, which | |
registers callbacks to receive either a promise’s eventual value or the reason | |
why the promise cannot be fulfilled. | |
Terminology | |
----------- | |
- `promise` is an object or function with a `then` method whose behavior conforms to this specification. | |
- `thenable` is an object or function that defines a `then` method. | |
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise). | |
- `exception` is a value that is thrown using the throw statement. | |
- `reason` is a value that indicates why a promise was rejected. | |
- `settled` the final resting state of a promise, fulfilled or rejected. | |
A promise can be in one of three states: pending, fulfilled, or rejected. | |
Promises that are fulfilled have a fulfillment value and are in the fulfilled | |
state. Promises that are rejected have a rejection reason and are in the | |
rejected state. A fulfillment value is never a thenable. | |
Promises can also be said to *resolve* a value. If this value is also a | |
promise, then the original promise's settled state will match the value's | |
settled state. So a promise that *resolves* a promise that rejects will | |
itself reject, and a promise that *resolves* a promise that fulfills will | |
itself fulfill. | |
Basic Usage: | |
------------ | |
```js | |
var promise = new Promise(function(resolve, reject) { | |
// on success | |
resolve(value); | |
// on failure | |
reject(reason); | |
}); | |
promise.then(function(value) { | |
// on fulfillment | |
}, function(reason) { | |
// on rejection | |
}); | |
``` | |
Advanced Usage: | |
--------------- | |
Promises shine when abstracting away asynchronous interactions such as | |
`XMLHttpRequest`s. | |
```js | |
function getJSON(url) { | |
return new Promise(function(resolve, reject){ | |
var xhr = new XMLHttpRequest(); | |
xhr.open('GET', url); | |
xhr.onreadystatechange = handler; | |
xhr.responseType = 'json'; | |
xhr.setRequestHeader('Accept', 'application/json'); | |
xhr.send(); | |
function handler() { | |
if (this.readyState === this.DONE) { | |
if (this.status === 200) { | |
resolve(this.response); | |
} else { | |
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']')); | |
} | |
} | |
}; | |
}); | |
} | |
getJSON('/posts.json').then(function(json) { | |
// on fulfillment | |
}, function(reason) { | |
// on rejection | |
}); | |
``` | |
Unlike callbacks, promises are great composable primitives. | |
```js | |
Promise.all([ | |
getJSON('/posts'), | |
getJSON('/comments') | |
]).then(function(values){ | |
values[0] // => postsJSON | |
values[1] // => commentsJSON | |
return values; | |
}); | |
``` | |
@class Promise | |
@param {function} resolver | |
@param {String} label optional string for labeling the promise. | |
Useful for tooling. | |
@constructor | |
*/ | |
function Promise(resolver, label) { | |
this._id = counter++; | |
this._label = label; | |
this._state = undefined; | |
this._result = undefined; | |
this._subscribers = []; | |
if (noop !== resolver) { | |
if (!isFunction(resolver)) { | |
needsResolver(); | |
} | |
if (!(this instanceof Promise)) { | |
needsNew(); | |
} | |
initializePromise(this, resolver); | |
} | |
} | |
Promise.all = all; | |
Promise.race = race; | |
Promise.resolve = Resolve; | |
Promise.reject = Reject; | |
Promise.prototype = { | |
constructor: Promise, | |
/** | |
The primary way of interacting with a promise is through its `then` method, | |
which registers callbacks to receive either a promise's eventual value or the | |
reason why the promise cannot be fulfilled. | |
```js | |
findUser().then(function(user){ | |
// user is available | |
}, function(reason){ | |
// user is unavailable, and you are given the reason why | |
}); | |
``` | |
Chaining | |
-------- | |
The return value of `then` is itself a promise. This second, 'downstream' | |
promise is resolved with the return value of the first promise's fulfillment | |
or rejection handler, or rejected if the handler throws an exception. | |
```js | |
findUser().then(function (user) { | |
return user.name; | |
}, function (reason) { | |
return 'default name'; | |
}).then(function (userName) { | |
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it | |
// will be `'default name'` | |
}); | |
findUser().then(function (user) { | |
throw new Error('Found user, but still unhappy'); | |
}, function (reason) { | |
throw new Error('`findUser` rejected and we're unhappy'); | |
}).then(function (value) { | |
// never reached | |
}, function (reason) { | |
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'. | |
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'. | |
}); | |
``` | |
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream. | |
```js | |
findUser().then(function (user) { | |
throw new PedagogicalException('Upstream error'); | |
}).then(function (value) { | |
// never reached | |
}).then(function (value) { | |
// never reached | |
}, function (reason) { | |
// The `PedgagocialException` is propagated all the way down to here | |
}); | |
``` | |
Assimilation | |
------------ | |
Sometimes the value you want to propagate to a downstream promise can only be | |
retrieved asynchronously. This can be achieved by returning a promise in the | |
fulfillment or rejection handler. The downstream promise will then be pending | |
until the returned promise is settled. This is called *assimilation*. | |
```js | |
findUser().then(function (user) { | |
return findCommentsByAuthor(user); | |
}).then(function (comments) { | |
// The user's comments are now available | |
}); | |
``` | |
If the assimliated promise rejects, then the downstream promise will also reject. | |
```js | |
findUser().then(function (user) { | |
return findCommentsByAuthor(user); | |
}).then(function (comments) { | |
// If `findCommentsByAuthor` fulfills, we'll have the value here | |
}, function (reason) { | |
// If `findCommentsByAuthor` rejects, we'll have the reason here | |
}); | |
``` | |
Simple Example | |
-------------- | |
Synchronous Example | |
```javascript | |
var result; | |
try { | |
result = findResult(); | |
// success | |
} catch(reason) { | |
// failure | |
} | |
``` | |
Errback Example | |
```js | |
findResult(function(result, err){ | |
if (err) { | |
// failure | |
} else { | |
// success | |
} | |
}); | |
``` | |
Promise Example; | |
```javascript | |
findResult().then(function(result){ | |
// success | |
}, function(reason){ | |
// failure | |
}); | |
``` | |
Advanced Example | |
-------------- | |
Synchronous Example | |
```javascript | |
var author, books; | |
try { | |
author = findAuthor(); | |
books = findBooksByAuthor(author); | |
// success | |
} catch(reason) { | |
// failure | |
} | |
``` | |
Errback Example | |
```js | |
function foundBooks(books) { | |
} | |
function failure(reason) { | |
} | |
findAuthor(function(author, err){ | |
if (err) { | |
failure(err); | |
// failure | |
} else { | |
try { | |
findBoooksByAuthor(author, function(books, err) { | |
if (err) { | |
failure(err); | |
} else { | |
try { | |
foundBooks(books); | |
} catch(reason) { | |
failure(reason); | |
} | |
} | |
}); | |
} catch(error) { | |
failure(err); | |
} | |
// success | |
} | |
}); | |
``` | |
Promise Example; | |
```javascript | |
findAuthor(). | |
then(findBooksByAuthor). | |
then(function(books){ | |
// found books | |
}).catch(function(reason){ | |
// something went wrong | |
}); | |
``` | |
@method then | |
@param {Function} onFulfilled | |
@param {Function} onRejected | |
@param {String} label optional string for labeling the promise. | |
Useful for tooling. | |
@return {Promise} | |
*/ | |
then: function(onFulfillment, onRejection, label) { | |
var parent = this; | |
var state = parent._state; | |
if (state === FULFILLED && !onFulfillment || state === REJECTED && !onRejection) { | |
return this; | |
} | |
parent._onerror = null; | |
var child = new this.constructor(noop, label); | |
var result = parent._result; | |
if (state) { | |
var callback = arguments[state - 1]; | |
asap(function(){ | |
invokeCallback(state, child, callback, result); | |
}); | |
} else { | |
subscribe(parent, child, onFulfillment, onRejection); | |
} | |
return child; | |
}, | |
/** | |
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same | |
as the catch block of a try/catch statement. | |
```js | |
function findAuthor(){ | |
throw new Error('couldn't find that author'); | |
} | |
// synchronous | |
try { | |
findAuthor(); | |
} catch(reason) { | |
// something went wrong | |
} | |
// async with promises | |
findAuthor().catch(function(reason){ | |
// something went wrong | |
}); | |
``` | |
@method catch | |
@param {Function} onRejection | |
@param {String} label optional string for labeling the promise. | |
Useful for tooling. | |
@return {Promise} | |
*/ | |
'catch': function(onRejection, label) { | |
return this.then(null, onRejection, label); | |
} | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export function objectOrFunction(x) { | |
return typeof x === 'function' || (typeof x === 'object' && x !== null); | |
} | |
export function isFunction(x) { | |
return typeof x === 'function'; | |
} | |
export function isMaybeThenable(x) { | |
return typeof x === 'object' && x !== null; | |
} | |
var _isArray; | |
if (!Array.isArray) { | |
_isArray = function (x) { | |
return Object.prototype.toString.call(x) === '[object Array]'; | |
}; | |
} else { | |
_isArray = Array.isArray; | |
} | |
export var isArray = _isArray; | |
// Date.now is not available in browsers < IE9 | |
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now#Compatibility | |
export var now = Date.now || function() { return new Date().getTime(); }; | |
function F() { } | |
export var o_create = (Object.create || function (o) { | |
if (arguments.length > 1) { | |
throw new Error('Second argument not supported'); | |
} | |
if (typeof o !== 'object') { | |
throw new TypeError('Argument must be an object'); | |
} | |
F.prototype = o; | |
return new F(); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment