pax_global_header 0000666 0000000 0000000 00000000064 13476252164 0014524 g ustar 00root root 0000000 0000000 52 comment=1e68dce6f674e5613f4a1797aedd55dc70ac1dcb
es6-promise-4.2.8/ 0000775 0000000 0000000 00000000000 13476252164 0013710 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/.eslintrc 0000664 0000000 0000000 00000001566 13476252164 0015544 0 ustar 00root root 0000000 0000000 {
"extends": "ember",
"parser": "babel-eslint",
"ecmaFeatures": {
modules: true,
blockBindings: true,
arrowFunctions: true,
objectLiteralShorthandMethods: true,
objectLiteralShorthandProperties: true,
templateStrings: true
},
"rules": {
"indent": [ 2, "tab", { "SwitchCase": 1 } ],
"object-shorthand": [ 2, "always" ],
"prefer-const": 0,
"comma-dangle": 0,
"spaced-comment": 1,
"object-curly-spacing": [2, "always"],
"arrow-spacing": [ 1, { before: true, after: true } ],
"array-bracket-spacing": [ 2, "always" ],
"no-restricted-syntax": 0,
"no-warning-comments": [ 0, { "terms": [ "todo", "fixme", "xxx" ], "location": "start" } ],
"no-ternary": 0,
"no-nested-ternary": 2,
"brace-style": [ 2, "stroustrup" ],
"no-else-return": 0
}
}
es6-promise-4.2.8/.gitignore 0000664 0000000 0000000 00000000070 13476252164 0015675 0 ustar 00root root 0000000 0000000 /node_modules
/promises_tests
/main.js
/tmp
/docs
/dist
es6-promise-4.2.8/.jshintrc 0000664 0000000 0000000 00000001455 13476252164 0015542 0 ustar 00root root 0000000 0000000 {
"predef": [
"console",
"require",
"equal",
"test",
"testBoth",
"testWithDefault",
"raises",
"deepEqual",
"start",
"stop",
"ok",
"strictEqual",
"module",
"expect"
],
"esnext": true,
"proto": true,
"node" : true,
"browser" : true,
"boss" : true,
"curly": false,
"debug": false,
"devel": false,
"eqeqeq": true,
"evil": true,
"forin": false,
"immed": false,
"laxbreak": false,
"newcap": true,
"noarg": true,
"noempty": false,
"nonew": false,
"nomen": false,
"onevar": false,
"plusplus": false,
"regexp": false,
"undef": true,
"sub": true,
"strict": false,
"white": false,
"eqnull": true
}
es6-promise-4.2.8/.release.json 0000664 0000000 0000000 00000000736 13476252164 0016307 0 ustar 00root root 0000000 0000000 {
"non-interactive": true,
"dry-run": false,
"verbose": false,
"force": false,
"pkgFiles": ["package.json", "bower.json"],
"increment": "patch",
"commitMessage": "Release %s",
"tagName": "v%s",
"tagAnnotation": "Release %s",
"buildCommand": "npm run-script build:production",
"dist": {
"repo": "git@github.com:components/es6-promise.git",
"stageDir": "tmp/stage",
"base": "dist",
"files": ["**/*", "../package.json", "../bower.json"]
}
}
es6-promise-4.2.8/.spmignore 0000664 0000000 0000000 00000000167 13476252164 0015720 0 ustar 00root root 0000000 0000000 /node_modules/
/tmp
/tasks
/test
/vendor
/.jshintrc
/.npmignore
/.travis.yml
/Gruntfile.js
/component.json
/index.html
es6-promise-4.2.8/.travis.yml 0000664 0000000 0000000 00000000372 13476252164 0016023 0 ustar 00root root 0000000 0000000 language: node_js
node_js:
- "9"
- "8"
- "6"
- "4"
before_install:
- nvm install 6
- nvm use 6
- export PATH=/usr/local/phantomjs-2.0.0/bin:$PATH
before_script:
- nvm use $TRAVIS_NODE_VERSION
env:
global:
- EMBER_ENV=production
es6-promise-4.2.8/Brocfile.js 0000664 0000000 0000000 00000005770 13476252164 0016004 0 ustar 00root root 0000000 0000000 'use strict';
/* jshint node:true, undef:true, unused:true */
const Rollup = require('broccoli-rollup');
const Babel = require('broccoli-babel-transpiler');
const merge = require('broccoli-merge-trees');
const uglify = require('broccoli-uglify-js');
const version = require('git-repo-version');
const watchify = require('broccoli-watchify');
const concat = require('broccoli-concat');
const fs = require('fs');
const stew = require('broccoli-stew');
const find = stew.find;
const mv = stew.mv;
const rename = stew.rename;
const env = stew.env;
const map = stew.map;
const lib = find('lib');
// test stuff
const testDir = find('test');
const testFiles = find('test/{index.html,worker.js}');
const json3 = mv(find('node_modules/json3/lib/{json3.js}'), 'node_modules/json3/lib/', 'test/');
// mocha doesn't browserify correctly
const mocha = mv(find('node_modules/mocha/mocha.{js,css}'), 'node_modules/mocha/', 'test/');
const testVendor = merge([ json3, mocha ]);
const es5 = new Babel(lib, {
plugins: [
'transform-es2015-arrow-functions',
'transform-es2015-computed-properties',
'transform-es2015-shorthand-properties',
'transform-es2015-template-literals',
'transform-es2015-parameters',
'transform-es2015-destructuring',
'transform-es2015-spread',
'transform-es2015-block-scoping',
'transform-es2015-constants',
['transform-es2015-classes', { loose: true }],
'babel6-plugin-strip-class-callcheck'
]
});
function rollupConfig(entry) {
return new Rollup(es5, {
rollup: {
input: 'lib/' + entry,
output: [
{
format: 'umd',
name: 'ES6Promise',
file: entry,
sourcemap: 'inline'
}
]
}
});
}
// build RSVP itself
const es6Promise = rollupConfig('es6-promise.js')
const es6PromiseAuto = rollupConfig('es6-promise.auto.js')
const testBundle = watchify(merge([
mv(es6Promise, 'test'),
testDir
]), {
browserify: { debug: true, entries: ['./test/index.js'] }
});
const header = stew.map(find('config/versionTemplate.txt'), content => content.replace(/VERSION_PLACEHOLDER_STRING/, version()));
function concatAs(outputFile) {
return merge([
concat(merge([es6Promise, header]), {
headerFiles: ['config/versionTemplate.txt'],
inputFiles: ['es6-promise.js'],
outputFile: outputFile
}),
concat(merge([es6PromiseAuto, header]), {
headerFiles: ['config/versionTemplate.txt'],
inputFiles: ['es6-promise.auto.js'],
outputFile: outputFile.replace('es6-promise', 'es6-promise.auto'),
}),
]);
}
function production() {
let result;
env('production', () => {
result = uglify(concatAs('es6-promise.min.js'), {
compress: true,
mangle: true,
});
})
return result;
}
function development() {
return concatAs('es6-promise.js');
}
module.exports = merge([
merge([
production(),
development(),
].filter(Boolean)),
// test stuff
testFiles,
testVendor,
mv(testBundle, 'test')
]);
es6-promise-4.2.8/CHANGELOG.md 0000664 0000000 0000000 00000007032 13476252164 0015523 0 ustar 00root root 0000000 0000000 # Master
# 4.2.5
* remove old try/catch performance hacks, modern runtimes do not require these tricks
# 4.2.4
* [Fixes #305] Confuse webpack
# 4.2.3
* Cleanup testem related build configuration
* Use `prepublishOnly` instead of `prepublish` (thanks @rhysd)
* Add Node.js 9, 8 to testing matrix
* drop now unused s3 deployment files
* internal cleanup (thanks to @bekzod, @mariusschulz)
* Fixup Changelog
# 4.2.2
* Ensure PROMISE_ID works correctly
* internal cleanup (thanks yo @mariusschulz)
# 4.2.1
* drop bower support
# 4.2.0
* drop `dist` from git repo
* add `Promise.prototype.finally`
* update various build related dependencies
* add CDN links
# 4.1.0
* [BUGFIX] Fix memory leak [#269]
* [BUGFIX] Auto Bundles within an AMD Environment [#263]
# 4.0.5
* fix require('es6-promise/auto') for Node < 4
# 4.0.4
* fix asap when using https://github.com/Kinvey/titanium-sdk
# 4.0.3
* fix Readme links
# 4.0.2
* fix require('es6-promise/auto');
# 4.0.0
* no longer polyfill automatically, if needed one can still invoke
`require('es6-promise/auto')` directly.
# 3.3.1
* fix links in readme
# 3.3.0
* support polyfil on WebMAF (playstation env)
* fix tampering related bug global `constructor` was referenced by mistake.
* provide TS Typings
* increase compatibliity with sinon.useFakeTimers();
* update build tools (use rollup)
* directly export promise;
# 3.2.2
* IE8: use isArray
* update build dependencies
# 3.2.1
* fix race tampering issue
* use eslint
* fix Promise.all tampering
* remove unused code
* fix issues with NWJS/electron
# 3.2.0
* improve tamper resistence of Promise.all Promise.race and
Promise.prototype.then (note, this isn't complete, but addresses an exception
when used \w core-js, follow up work will address entirely)
* remove spec incompatible then chaining fast-path
* add eslint
* update build deps
# 3.1.2
* fix node detection issues with NWJS/electron
# 3.1.0
* improve performance of Promise.all when it encounters a non-promise input object input
* then/resolve tamper protection
* reduce AST size of promise constructor, to facilitate more inlining
* Update README.md with details about PhantomJS requirement for running tests
* Mangle and compress the minified version
# 3.0.2
* correctly bump both bower and package.json versions
# 3.0.1
* no longer include dist/test in npm releases
# 3.0.0
* use nextTick() instead of setImmediate() to schedule microtasks with node 0.10. Later versions of
nodes are not affected as they were already using nextTick(). Note that using nextTick() might
trigger a depreciation warning on 0.10 as described at https://github.com/cujojs/when/issues/410.
The reason why nextTick() is preferred is that is setImmediate() would schedule a macrotask
instead of a microtask and might result in a different scheduling.
If needed you can revert to the former behavior as follow:
var Promise = require('es6-promise').Promise;
Promise._setScheduler(setImmediate);
# 2.3.0
* #121: Ability to override the internal asap implementation
* #120: Use an ascii character for an apostrophe, for source maps
# 2.2.0
* #116: Expose asap() and a way to override the scheduling mechanism on Promise
* Lock to v0.2.3 of ember-cli
# 2.1.1
* Fix #100 via #105: tell browserify to ignore vertx require
* Fix #101 via #102: "follow thenable state, not own state"
# 2.1.0
* #59: Automatic polyfill. No need to invoke `ES6Promise.polyfill()` anymore.
* ... (see the commit log)
# 2.0.0
* re-sync with RSVP. Many large performance improvements and bugfixes.
# 1.0.0
* first subset of RSVP
es6-promise-4.2.8/LICENSE 0000664 0000000 0000000 00000002111 13476252164 0014710 0 ustar 00root root 0000000 0000000 Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
es6-promise-4.2.8/README.md 0000664 0000000 0000000 00000006247 13476252164 0015200 0 ustar 00root root 0000000 0000000 # ES6-Promise (subset of [rsvp.js](https://github.com/tildeio/rsvp.js)) [](https://travis-ci.org/stefanpenner/es6-promise)
This is a polyfill of the [ES6 Promise](http://www.ecma-international.org/ecma-262/6.0/#sec-promise-constructor). The implementation is a subset of [rsvp.js](https://github.com/tildeio/rsvp.js) extracted by @jakearchibald, if you're wanting extra features and more debugging options, check out the [full library](https://github.com/tildeio/rsvp.js).
For API details and how to use promises, see the JavaScript Promises HTML5Rocks article.
## Downloads
* [es6-promise 27.86 KB (7.33 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.js)
* [es6-promise-auto 27.78 KB (7.3 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.js) - Automatically provides/replaces `Promise` if missing or broken.
* [es6-promise-min 6.17 KB (2.4 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.min.js)
* [es6-promise-auto-min 6.19 KB (2.4 KB gzipped)](https://cdn.jsdelivr.net/npm/es6-promise/dist/es6-promise.auto.min.js) - Minified version of `es6-promise-auto` above.
## CDN
To use via a CDN include this in your html:
```html
```
## Node.js
To install:
```sh
yarn add es6-promise
```
or
```sh
npm install es6-promise
```
To use:
```js
var Promise = require('es6-promise').Promise;
```
## Usage in IE<9
`catch` and `finally` are reserved keywords in IE<9, meaning
`promise.catch(func)` or `promise.finally(func)` throw a syntax error. To work
around this, you can use a string to access the property as shown in the
following example.
However most minifiers will automatically fix this for you, making the
resulting code safe for old browsers and production:
```js
promise['catch'](function(err) {
// ...
});
```
```js
promise['finally'](function() {
// ...
});
```
## Auto-polyfill
To polyfill the global environment (either in Node or in the browser via CommonJS) use the following code snippet:
```js
require('es6-promise').polyfill();
```
Alternatively
```js
require('es6-promise/auto');
```
Notice that we don't assign the result of `polyfill()` to any variable. The `polyfill()` method will patch the global environment (in this case to the `Promise` name) when called.
## Building & Testing
You will need to have PhantomJS installed globally in order to run the tests.
`npm install -g phantomjs`
* `npm run build` to build
* `npm test` to run tests
* `npm start` to run a build watcher, and webserver to test
* `npm run test:server` for a testem test runner and watching builder
es6-promise-4.2.8/auto.js 0000664 0000000 0000000 00000000263 13476252164 0015217 0 ustar 00root root 0000000 0000000 // This file can be required in Browserify and Node.js for automatic polyfill
// To use it: require('es6-promise/auto');
'use strict';
module.exports = require('./').polyfill();
es6-promise-4.2.8/config/ 0000775 0000000 0000000 00000000000 13476252164 0015155 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/config/versionTemplate.txt 0000664 0000000 0000000 00000000570 13476252164 0021101 0 ustar 00root root 0000000 0000000 /*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version VERSION_PLACEHOLDER_STRING
*/
es6-promise-4.2.8/es6-promise.d.ts 0000664 0000000 0000000 00000012331 13476252164 0016653 0 ustar 00root root 0000000 0000000 export interface Thenable {
then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Thenable;
then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Thenable;
}
export class Promise implements Thenable {
/**
* If you call resolve in the body of the callback passed to the constructor,
* your promise is fulfilled with result object passed to resolve.
* If you call reject your promise is rejected with the object passed to resolve.
* For consistency and debugging (eg stack traces), obj should be an instanceof Error.
* Any errors thrown in the constructor callback will be implicitly passed to reject().
*/
constructor (callback: (resolve : (value?: R | Thenable) => void, reject: (error?: any) => void) => void);
/**
* onFulfilled is called when/if "promise" resolves. onRejected is called when/if "promise" rejects.
* Both are optional, if either/both are omitted the next onFulfilled/onRejected in the chain is called.
* Both callbacks have a single parameter , the fulfillment value or rejection reason.
* "then" returns a new promise equivalent to the value you return from onFulfilled/onRejected after being passed through Promise.resolve.
* If an error is thrown in the callback, the returned promise rejects with that error.
*
* @param onFulfilled called when/if "promise" resolves
* @param onRejected called when/if "promise" rejects
*/
then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => U | Thenable): Promise;
then (onFulfilled?: (value: R) => U | Thenable, onRejected?: (error: any) => void): Promise;
/**
* Sugar for promise.then(undefined, onRejected)
*
* @param onRejected called when/if "promise" rejects
*/
catch (onRejected?: (error: any) => U | Thenable): Promise;
/**
* onSettled is invoked when/if the "promise" settles (either rejects or fulfills).
* The returned promise is settled when the `Thenable` returned by `onFinally` settles;
* it is rejected if `onFinally` throws or rejects; otherwise it assumes the state of the
* original Promise.
*
* @param onFinally called when/if "promise" settles
*/
finally (onFinally?: () => any | Thenable): Promise;
/**
* Make a new promise from the thenable.
* A thenable is promise-like in as far as it has a "then" method.
*/
static resolve (): Promise;
static resolve (value: R | Thenable): Promise;
/**
* Make a promise that rejects to obj. For consistency and debugging (eg stack traces), obj should be an instanceof Error
*/
static reject (error: any): Promise;
/**
* Make a promise that fulfills when every item in the array fulfills, and rejects if (and when) any item rejects.
* the array passed to all can be a mixture of promise-like objects and other objects.
* The fulfillment value is an array (in order) of fulfillment values. The rejection value is the first rejection value.
*/
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable, T10 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable, T9 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable, T8 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable, T7 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable, T6 | Thenable]): Promise<[T1, T2, T3, T4, T5, T6]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable , T5 | Thenable]): Promise<[T1, T2, T3, T4, T5]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable, T4 | Thenable ]): Promise<[T1, T2, T3, T4]>;
static all(values: [T1 | Thenable, T2 | Thenable, T3 | Thenable]): Promise<[T1, T2, T3]>;
static all(values: [T1 | Thenable, T2 | Thenable]): Promise<[T1, T2]>;
static all(values: [T1 | Thenable]): Promise<[T1]>;
static all(values: Array>): Promise;
/**
* Make a Promise that fulfills when any item fulfills, and rejects if any item rejects.
*/
static race (promises: (R | Thenable)[]): Promise;
}
/**
* The polyfill method will patch the global environment (in this case to the Promise name) when called.
*/
export function polyfill (): void;
es6-promise-4.2.8/lib/ 0000775 0000000 0000000 00000000000 13476252164 0014456 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/lib/es6-promise.auto.js 0000664 0000000 0000000 00000000121 13476252164 0020126 0 ustar 00root root 0000000 0000000 import Promise from './es6-promise';
Promise.polyfill();
export default Promise;
es6-promise-4.2.8/lib/es6-promise.js 0000664 0000000 0000000 00000000301 13476252164 0017157 0 ustar 00root root 0000000 0000000 import Promise from './es6-promise/promise';
import polyfill from './es6-promise/polyfill';
// Strange compat..
Promise.polyfill = polyfill;
Promise.Promise = Promise;
export default Promise;
es6-promise-4.2.8/lib/es6-promise/ 0000775 0000000 0000000 00000000000 13476252164 0016627 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/lib/es6-promise/-internal.js 0000664 0000000 0000000 00000012301 13476252164 0021053 0 ustar 00root root 0000000 0000000 import {
objectOrFunction,
isFunction
} from './utils';
import {
asap
} from './asap';
import originalThen from './then';
import originalResolve from './promise/resolve';
export const PROMISE_ID = Math.random().toString(36).substring(2);
function noop() {}
const PENDING = void 0;
const FULFILLED = 1;
const REJECTED = 2;
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function tryThen(then, value, fulfillmentHandler, rejectionHandler) {
try {
then.call(value, fulfillmentHandler, rejectionHandler);
} catch(e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then) {
asap(promise => {
let sealed = false;
let error = tryThen(then, thenable, value => {
if (sealed) { return; }
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, 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 (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, value => resolve(promise, value),
reason => reject(promise, reason))
}
}
function handleMaybeThenable(promise, maybeThenable, then) {
if (maybeThenable.constructor === promise.constructor &&
then === originalThen &&
maybeThenable.constructor.resolve === originalResolve) {
handleOwnThenable(promise, maybeThenable);
} 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, selfFulfillment());
} else if (objectOrFunction(value)) {
let then;
try {
then = value.then;
} catch (error) {
reject(promise, error);
return;
}
handleMaybeThenable(promise, value, then);
} 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) {
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) {
let { _subscribers } = parent;
let { length } = _subscribers;
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) {
let subscribers = promise._subscribers;
let settled = promise._state;
if (subscribers.length === 0) { return; }
let child, callback, detail = promise._result;
for (let 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 invokeCallback(settled, promise, callback, detail) {
let hasCallback = isFunction(callback),
value, error, succeeded = true;
if (hasCallback) {
try {
value = callback(detail);
} catch (e) {
succeeded = false;
error = e;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (succeeded === false) {
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);
}
}
let id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
export {
nextId,
makePromise,
noop,
resolve,
reject,
fulfill,
subscribe,
publish,
publishRejection,
initializePromise,
invokeCallback,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
};
es6-promise-4.2.8/lib/es6-promise/asap.js 0000664 0000000 0000000 00000006143 13476252164 0020115 0 ustar 00root root 0000000 0000000 let len = 0;
let vertxNext;
let customSchedulerFn;
export var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, 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.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
}
export function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
export function setAsap(asapFn) {
asap = asapFn;
}
const browserWindow = (typeof window !== 'undefined') ? window : undefined;
const browserGlobal = browserWindow || {};
const BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
const isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
const isWorker = typeof Uint8ClampedArray !== 'undefined' &&
typeof importScripts !== 'undefined' &&
typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return () => process.nextTick(flush);
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function() {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
let iterations = 0;
const observer = new BrowserMutationObserver(flush);
const node = document.createTextNode('');
observer.observe(node, { characterData: true });
return () => {
node.data = (iterations = ++iterations % 2);
};
}
// web worker
function useMessageChannel() {
const channel = new MessageChannel();
channel.port1.onmessage = flush;
return () => channel.port2.postMessage(0);
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
const globalSetTimeout = setTimeout;
return () => globalSetTimeout(flush, 1);
}
const queue = new Array(1000);
function flush() {
for (let i = 0; i < len; i+=2) {
let callback = queue[i];
let arg = queue[i+1];
callback(arg);
queue[i] = undefined;
queue[i+1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
const vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch(e) {
return useSetTimeout();
}
}
let scheduleFlush;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
es6-promise-4.2.8/lib/es6-promise/enumerator.js 0000664 0000000 0000000 00000005442 13476252164 0021353 0 ustar 00root root 0000000 0000000 import {
isArray,
isMaybeThenable
} from './utils';
import {
noop,
reject,
fulfill,
subscribe,
FULFILLED,
REJECTED,
PENDING,
handleMaybeThenable
} from './-internal';
import then from './then';
import Promise from './promise';
import originalResolve from './promise/resolve';
import originalThen from './then';
import { makePromise, PROMISE_ID } from './-internal';
function validationError() {
return new Error('Array Methods must be provided an Array');
};
export default class Enumerator {
constructor(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
_enumerate(input) {
for (let i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
}
_eachEntry(entry, i) {
let c = this._instanceConstructor;
let { resolve } = c;
if (resolve === originalResolve) {
let then;
let error;
let didError = false;
try {
then = entry.then;
} catch (e) {
didError = true;
error = e;
}
if (then === originalThen &&
entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise) {
let promise = new c(noop);
if (didError) {
reject(promise, error);
} else {
handleMaybeThenable(promise, entry, then);
}
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(resolve => resolve(entry)), i);
}
} else {
this._willSettleAt(resolve(entry), i);
}
}
_settledAt(state, i, value) {
let { promise } = this;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
}
_willSettleAt(promise, i) {
let enumerator = this;
subscribe(
promise, undefined,
value => enumerator._settledAt(FULFILLED, i, value),
reason => enumerator._settledAt(REJECTED, i, reason)
);
}
};
es6-promise-4.2.8/lib/es6-promise/polyfill.js 0000664 0000000 0000000 00000001324 13476252164 0021017 0 ustar 00root root 0000000 0000000 /*global self*/
import Promise from './promise';
export default function polyfill() {
let local;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
let P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch(e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast){
return;
}
}
local.Promise = Promise;
}
es6-promise-4.2.8/lib/es6-promise/promise.js 0000664 0000000 0000000 00000023501 13476252164 0020644 0 ustar 00root root 0000000 0000000 import {
isFunction
} from './utils';
import {
noop,
nextId,
PROMISE_ID,
initializePromise
} from './-internal';
import {
asap,
setAsap,
setScheduler
} from './asap';
import all from './promise/all';
import race from './promise/race';
import Resolve from './promise/resolve';
import Reject from './promise/reject';
import then from './then';
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.");
}
/**
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
let 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){
let 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
Useful for tooling.
@constructor
*/
class Promise {
constructor(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
/**
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
let 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
let 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
Useful for tooling.
@return {Promise}
*/
/**
`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
Useful for tooling.
@return {Promise}
*/
catch(onRejection) {
return this.then(null, onRejection);
}
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuther();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@return {Promise}
*/
finally(callback) {
let promise = this;
let constructor = promise.constructor;
if ( isFunction(callback) ) {
return promise.then(value => constructor.resolve(callback()).then(() => value),
reason => constructor.resolve(callback()).then(() => { throw reason; }));
}
return promise.then(callback, callback);
}
}
Promise.prototype.then = then;
export default Promise;
Promise.all = all;
Promise.race = race;
Promise.resolve = Resolve;
Promise.reject = Reject;
Promise._setScheduler = setScheduler;
Promise._setAsap = setAsap;
Promise._asap = asap;
es6-promise-4.2.8/lib/es6-promise/promise/ 0000775 0000000 0000000 00000000000 13476252164 0020305 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/lib/es6-promise/promise/all.js 0000664 0000000 0000000 00000003043 13476252164 0021413 0 ustar 00root root 0000000 0000000 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
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let 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
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let 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) {
return new Enumerator(this, entries).promise;
}
es6-promise-4.2.8/lib/es6-promise/promise/race.js 0000664 0000000 0000000 00000004313 13476252164 0021556 0 ustar 00root root 0000000 0000000 import {
isArray
} from "../utils";
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let 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
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let 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
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) {
/*jshint validthis:true */
let Constructor = this;
if (!isArray(entries)) {
return new Constructor((_, reject) => reject(new TypeError('You must pass an array to race.')));
} else {
return new Constructor((resolve, reject) => {
let length = entries.length;
for (let i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
es6-promise-4.2.8/lib/es6-promise/promise/reject.js 0000664 0000000 0000000 00000002163 13476252164 0022121 0 ustar 00root root 0000000 0000000 import {
noop,
reject as _reject
} from '../-internal';
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let 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
let 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.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
export default function reject(reason) {
/*jshint validthis:true */
let Constructor = this;
let promise = new Constructor(noop);
_reject(promise, reason);
return promise;
}
es6-promise-4.2.8/lib/es6-promise/promise/resolve.js 0000664 0000000 0000000 00000002032 13476252164 0022317 0 ustar 00root root 0000000 0000000 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
let 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
let 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
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
export default function resolve(object) {
/*jshint validthis:true */
let Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
let promise = new Constructor(noop);
_resolve(promise, object);
return promise;
}
es6-promise-4.2.8/lib/es6-promise/then.js 0000664 0000000 0000000 00000001141 13476252164 0020120 0 ustar 00root root 0000000 0000000 import {
invokeCallback,
subscribe,
FULFILLED,
REJECTED,
noop,
makePromise,
PROMISE_ID
} from './-internal';
import { asap } from './asap';
export default function then(onFulfillment, onRejection) {
const parent = this;
const child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
const { _state } = parent;
if (_state) {
const callback = arguments[_state - 1];
asap(() => invokeCallback(_state, child, callback, parent._result));
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
es6-promise-4.2.8/lib/es6-promise/utils.js 0000664 0000000 0000000 00000000724 13476252164 0020330 0 ustar 00root root 0000000 0000000 export function objectOrFunction(x) {
let type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
export function isFunction(x) {
return typeof x === 'function';
}
export function isMaybeThenable(x) {
return x !== null && typeof x === 'object';
}
let _isArray;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = x => Object.prototype.toString.call(x) === '[object Array]';
}
export const isArray = _isArray;
es6-promise-4.2.8/package.json 0000664 0000000 0000000 00000004727 13476252164 0016210 0 ustar 00root root 0000000 0000000 {
"name": "es6-promise",
"description": "A lightweight library that provides tools for organizing asynchronous code",
"version": "4.2.8",
"author": "Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)",
"browser": {
"vertx": false
},
"bugs": {
"url": "https://github.com/stefanpenner/es6-promise/issues"
},
"dependencies": {},
"devDependencies": {
"babel-plugin-transform-es2015-arrow-functions": "^6.22.0",
"babel-plugin-transform-es2015-block-scoping": "^6.24.1",
"babel-plugin-transform-es2015-classes": "^6.24.1",
"babel-plugin-transform-es2015-computed-properties": "^6.24.1",
"babel-plugin-transform-es2015-constants": "^6.1.4",
"babel-plugin-transform-es2015-destructuring": "^6.23.0",
"babel-plugin-transform-es2015-parameters": "^6.24.1",
"babel-plugin-transform-es2015-shorthand-properties": "^6.24.1",
"babel-plugin-transform-es2015-spread": "^6.22.0",
"babel-plugin-transform-es2015-template-literals": "^6.22.0",
"babel6-plugin-strip-class-callcheck": "^6.0.0",
"broccoli-babel-transpiler": "^6.0.0",
"broccoli-concat": "^3.1.0",
"broccoli-merge-trees": "^2.0.0",
"broccoli-rollup": "^2.0.0",
"broccoli-stew": "^1.5.0",
"broccoli-uglify-js": "^0.2.0",
"broccoli-watchify": "^1.0.1",
"ember-cli": "2.18.0-beta.2",
"ember-cli-dependency-checker": "^2.1.0",
"git-repo-version": "1.0.1",
"json3": "^3.3.2",
"mocha": "^4.0.1",
"promises-aplus-tests-phantom": "^2.1.0-revise"
},
"directories": {
"lib": "lib"
},
"files": [
"dist",
"lib",
"es6-promise.d.ts",
"auto.js",
"!dist/test"
],
"homepage": "https://github.com/stefanpenner/es6-promise",
"jsdelivr": "dist/es6-promise.auto.min.js",
"keywords": [
"futures",
"polyfill",
"promise",
"promises"
],
"license": "MIT",
"main": "dist/es6-promise.js",
"namespace": "es6-promise",
"repository": {
"type": "git",
"url": "git://github.com/stefanpenner/es6-promise.git"
},
"scripts": {
"build": "ember build --environment production",
"prepublishOnly": "ember build --environment production",
"start": "ember s",
"test": "ember test",
"test:browser": "ember test --launch PhantomJS",
"test:node": "ember test --launch Mocha",
"test:server": "ember test --server"
},
"spm": {
"main": "dist/es6-promise.js"
},
"typings": "es6-promise.d.ts",
"unpkg": "dist/es6-promise.auto.min.js"
}
es6-promise-4.2.8/server/ 0000775 0000000 0000000 00000000000 13476252164 0015216 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/server/.jshintrc 0000664 0000000 0000000 00000000023 13476252164 0017036 0 ustar 00root root 0000000 0000000 {
"node": true
}
es6-promise-4.2.8/server/index.js 0000664 0000000 0000000 00000000151 13476252164 0016660 0 ustar 00root root 0000000 0000000 module.exports = function(app) {
app.get('/', function(req, res) {
res.redirect('/test/');
})
};
es6-promise-4.2.8/test/ 0000775 0000000 0000000 00000000000 13476252164 0014667 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/test/extension-test.js 0000664 0000000 0000000 00000120611 13476252164 0020217 0 ustar 00root root 0000000 0000000 /*global describe, specify, it, assert */
if (typeof Object.getPrototypeOf !== "function") {
Object.getPrototypeOf = "".__proto__ === String.prototype
? function (object) {
return object.__proto__;
}
: function (object) {
// May break if the constructor has been tampered with
return object.constructor.prototype;
};
}
var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this;
var Promise = g.adapter.Promise;
var assert = require('assert');
describe('tampering', function() {
var resolve = Promise.resolve;
afterEach(function() {
Promise.resolve = resolve;
});
describe('then assimilation', function() {
it('tampered resolved and then', function() {
var one = Promise.resolve(1);
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
Promise.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
return one.then(function() {
return two;
}).then(function(value) {
assert.equal(thenCalled, 1, 'expected then to be called once');
assert.equal(resolveCalled, 0, 'expected resolve to be called once');
assert.equal(value, 2, 'expected fulfillment value to be 2');
});
});
it('tampered resolved', function() {
var one = Promise.resolve(1);
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
Promise.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
return one.then(function() {
return two;
}).then(function(value) {
assert.equal(resolveCalled, 0, 'expected resolve to be called once');
assert.equal(value, 2, 'expected fulfillment value to be 2');
});
});
describe('alternative constructor', function() {
it('tampered resolved and then', function() {
var one = Promise.resolve(1);
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
var invokedAlternativeConstructor = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
function AlternativeConstructor(executor) {
invokedAlternativeConstructor++;
var followers = this.followers = [];
executor(function(value) {
followers.forEach(function(onFulfillment) {
onFulfillment(value)
});
}, function() {
throw TypeError('No Rejections supported');
});
}
AlternativeConstructor.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
AlternativeConstructor.prototype.then = function(onFulfillment, onRejection) {
this.followers.push(onFulfillment);
};
AlternativeConstructor.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
one.constructor = AlternativeConstructor
return one.then(function() {
return two;
}).then(function(value) {
assert.equal(invokedAlternativeConstructor, 1, 'expected AlternativeConstructor to be invoked once');
assert.equal(thenCalled, 1, 'expected then to be called once');
assert.equal(resolveCalled, 0, 'expected resolve to be called once');
assert.equal(value, 2, 'expected fulfillment value to be 2');
});
});
});
describe('Promise.all', function() {
it('tampered resolved and then', function() {
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
Promise.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
return Promise.all([two]).then(function(value) {
assert.equal(thenCalled, 1);
assert.equal(resolveCalled, 1);
assert.deepEqual(value, [2]);
});
});
it('alternative constructor and tampered then', function() {
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
function AlternativeConstructor(executor) {
var followers = this.followers = [];
executor(function(value) {
followers.forEach(function(onFulfillment) {
onFulfillment(value)
});
}, function() {
throw TypeError('No Rejections supported');
});
}
AlternativeConstructor.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
AlternativeConstructor.prototype.then = function(onFulfillment, onRejection) {
this.followers.push(onFulfillment);
};
return Promise.all.call(AlternativeConstructor, [two]).then(function(value) {
assert.equal(thenCalled, 1);
assert.equal(resolveCalled, 1);
assert.deepEqual(value, [2]);
});
});
});
describe('core-js species test', function() {
it('foreign thenable has correct internal slots', function() {
var p = Promise.resolve();
function NewConstructor(it) {
it(function(){}, function(){})
}
p.constructor = NewConstructor;
var f = p.then(function(){});
assert(f instanceof NewConstructor);
});
});
describe('Promise.race', function() {
it('tampered resolved and then', function() {
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
Promise.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
return Promise.race([two]).then(function(value) {
assert.equal(thenCalled, 1);
assert.equal(resolveCalled, 1);
assert.deepEqual(value, 2);
});
});
it('alternative constructor and tampered then', function() {
var two = Promise.resolve(2);
var thenCalled = 0;
var resolveCalled = 0;
two.then = function() {
thenCalled++;
return Promise.prototype.then.apply(this, arguments);
};
function AlternativeConstructor(executor) {
var followers = this.followers = [];
executor(function(value) {
followers.forEach(function(onFulfillment) {
onFulfillment(value)
});
}, function() {
throw TypeError('No Rejections supported');
});
}
AlternativeConstructor.resolve = function(x) {
resolveCalled++;
return new Promise(function(resolve) { resolve(x); });
};
AlternativeConstructor.prototype.then = function(onFulfillment, onRejection) {
this.followers.push(onFulfillment);
};
return Promise.race.call(AlternativeConstructor, [two]).then(function(value) {
assert.equal(thenCalled, 1);
assert.equal(resolveCalled, 1);
assert.deepEqual(value, 2);
});
});
});
});
});
describe("extensions", function() {
describe("Promise constructor", function() {
it('should exist and have length 1', function() {
assert(Promise);
assert.equal(Promise.length, 1);
});
it('should fulfill if `resolve` is called with a value', function(done) {
var promise = new Promise(function(resolve) { resolve('value'); });
promise.then(function(value) {
assert.equal(value, 'value');
done();
});
});
it('should reject if `reject` is called with a reason', function(done) {
var promise = new Promise(function(resolve, reject) { reject('reason'); });
promise.then(function() {
assert(false);
done();
}, function(reason) {
assert.equal(reason, 'reason');
done();
});
});
it('should be a constructor', function() {
var promise = new Promise(function() {});
assert.equal(Object.getPrototypeOf(promise), Promise.prototype, '[[Prototype]] equals Promise.prototype');
assert.equal(promise.constructor, Promise, 'constructor property of instances is set correctly');
assert.equal(Promise.prototype.constructor, Promise, 'constructor property of prototype is set correctly');
});
it('should NOT work without `new`', function() {
assert.throws(function(){
Promise(function(resolve) { resolve('value'); });
}, TypeError)
});
it('should throw a `TypeError` if not given a function', function() {
assert.throws(function () {
new Promise();
}, TypeError);
assert.throws(function () {
new Promise({});
}, TypeError);
assert.throws(function () {
new Promise('boo!');
}, TypeError);
});
it('should reject on resolver exception', function(done) {
new Promise(function() {
throw 'error';
}).then(null, function(e) {
assert.equal(e, 'error');
done();
});
});
it('should not resolve multiple times', function(done) {
var resolver, rejector, fulfilled = 0, rejected = 0;
var thenable = {
then: function(resolve, reject) {
resolver = resolve;
rejector = reject;
}
};
var promise = new Promise(function(resolve) {
resolve(1);
});
promise.then(function(value){
return thenable;
}).then(function(value){
fulfilled++;
}, function(reason) {
rejected++;
});
setTimeout(function() {
resolver(1);
resolver(1);
rejector(1);
rejector(1);
setTimeout(function() {
assert.equal(fulfilled, 1);
assert.equal(rejected, 0);
done();
}, 20);
}, 20);
});
describe('assimilation', function() {
it('should assimilate if `resolve` is called with a fulfilled promise', function(done) {
var originalPromise = new Promise(function(resolve) { resolve('original value'); });
var promise = new Promise(function(resolve) { resolve(originalPromise); });
promise.then(function(value) {
assert.equal(value, 'original value');
done();
});
});
it('should assimilate if `resolve` is called with a rejected promise', function(done) {
var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); });
var promise = new Promise(function(resolve) { resolve(originalPromise); });
promise.then(function() {
assert(false);
done();
}, function(reason) {
assert.equal(reason, 'original reason');
done();
});
});
it('should assimilate if `resolve` is called with a fulfilled thenable', function(done) {
var originalThenable = {
then: function (onFulfilled) {
setTimeout(function() { onFulfilled('original value'); }, 0);
}
};
var promise = new Promise(function(resolve) { resolve(originalThenable); });
promise.then(function(value) {
assert.equal(value, 'original value');
done();
});
});
it('should assimilate if `resolve` is called with a rejected thenable', function(done) {
var originalThenable = {
then: function (onFulfilled, onRejected) {
setTimeout(function() { onRejected('original reason'); }, 0);
}
};
var promise = new Promise(function(resolve) { resolve(originalThenable); });
promise.then(function() {
assert(false);
done();
}, function(reason) {
assert.equal(reason, 'original reason');
done();
});
});
it('should assimilate two levels deep, for fulfillment of self fulfilling promises', function(done) {
var originalPromise, promise;
originalPromise = new Promise(function(resolve) {
setTimeout(function() {
resolve(originalPromise);
}, 0)
});
promise = new Promise(function(resolve) {
setTimeout(function() {
resolve(originalPromise);
}, 0);
});
promise.then(function(value) {
assert(false);
done();
}).catch(function(reason) {
assert.equal(reason.message, "You cannot resolve a promise with itself");
assert(reason instanceof TypeError);
done();
});
});
it('should assimilate two levels deep, for fulfillment', function(done) {
var originalPromise = new Promise(function(resolve) { resolve('original value'); });
var nextPromise = new Promise(function(resolve) { resolve(originalPromise); });
var promise = new Promise(function(resolve) { resolve(nextPromise); });
promise.then(function(value) {
assert.equal(value, 'original value');
done();
});
});
it('should assimilate two levels deep, for rejection', function(done) {
var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); });
var nextPromise = new Promise(function(resolve) { resolve(originalPromise); });
var promise = new Promise(function(resolve) { resolve(nextPromise); });
promise.then(function() {
assert(false);
done();
}, function(reason) {
assert.equal(reason, 'original reason');
done();
});
});
it('should assimilate three levels deep, mixing thenables and promises (fulfilled case)', function(done) {
var originalPromise = new Promise(function(resolve) { resolve('original value'); });
var intermediateThenable = {
then: function (onFulfilled) {
setTimeout(function() { onFulfilled(originalPromise); }, 0);
}
};
var promise = new Promise(function(resolve) { resolve(intermediateThenable); });
promise.then(function(value) {
assert.equal(value, 'original value');
done();
});
});
it('should assimilate three levels deep, mixing thenables and promises (rejected case)', function(done) {
var originalPromise = new Promise(function(resolve, reject) { reject('original reason'); });
var intermediateThenable = {
then: function (onFulfilled) {
setTimeout(function() { onFulfilled(originalPromise); }, 0);
}
};
var promise = new Promise(function(resolve) { resolve(intermediateThenable); });
promise.then(function() {
assert(false);
done();
}, function(reason) {
assert.equal(reason, 'original reason');
done();
});
});
});
});
describe('Promise.all', function() {
testAll(function(){
return Promise.all.apply(Promise, arguments);
});
});
function testAll(all) {
it('should exist', function() {
assert(all);
});
it('works with plan pojo input', function(done) {
all([
{}
]).then(function(result) {
assert.deepEqual(result, [{}]);
done();
});
});
it('throws when not passed an array', function(done) {
var nothing = assertRejection(all());
var string = assertRejection(all(''));
var object = assertRejection(all({}));
Promise.all([
nothing,
string,
object
]).then(function(){ done(); });
});
specify('fulfilled only after all of the other promises are fulfilled', function(done) {
var firstResolved, secondResolved, firstResolver, secondResolver;
var first = new Promise(function(resolve) {
firstResolver = resolve;
});
first.then(function() {
firstResolved = true;
});
var second = new Promise(function(resolve) {
secondResolver = resolve;
});
second.then(function() {
secondResolved = true;
});
setTimeout(function() {
firstResolver(true);
}, 0);
setTimeout(function() {
secondResolver(true);
}, 0);
all([first, second]).then(function() {
assert(firstResolved);
assert(secondResolved);
done();
});
});
specify('rejected as soon as a promise is rejected', function(done) {
var firstResolver, secondResolver;
var first = new Promise(function(resolve, reject) {
firstResolver = { resolve: resolve, reject: reject };
});
var second = new Promise(function(resolve, reject) {
secondResolver = { resolve: resolve, reject: reject };
});
setTimeout(function() {
firstResolver.reject({});
}, 0);
var firstWasRejected, secondCompleted;
first.catch(function(){
firstWasRejected = true;
});
second.then(function(){
secondCompleted = true;
}, function() {
secondCompleted = true;
});
all([first, second]).then(function() {
assert(false);
}, function() {
assert(firstWasRejected);
assert(!secondCompleted);
done();
});
});
specify('passes the resolved values of each promise to the callback in the correct order', function(done) {
var firstResolver, secondResolver, thirdResolver;
var first = new Promise(function(resolve, reject) {
firstResolver = { resolve: resolve, reject: reject };
});
var second = new Promise(function(resolve, reject) {
secondResolver = { resolve: resolve, reject: reject };
});
var third = new Promise(function(resolve, reject) {
thirdResolver = { resolve: resolve, reject: reject };
});
thirdResolver.resolve(3);
firstResolver.resolve(1);
secondResolver.resolve(2);
all([first, second, third]).then(function(results) {
assert(results.length === 3);
assert(results[0] === 1);
assert(results[1] === 2);
assert(results[2] === 3);
done();
});
});
specify('resolves an empty array passed to all()', function(done) {
all([]).then(function(results) {
assert(results.length === 0);
done();
});
});
specify('works with null', function(done) {
all([null]).then(function(results) {
assert.equal(results[0], null);
done();
});
});
specify('works with a mix of promises and thenables and non-promises', function(done) {
var promise = new Promise(function(resolve) { resolve(1); });
var syncThenable = { then: function (onFulfilled) { onFulfilled(2); } };
var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } };
var nonPromise = 4;
all([promise, syncThenable, asyncThenable, nonPromise]).then(function(results) {
assert.deepEqual(results, [1, 2, 3, 4]);
done();
}).catch(done);
});
}
describe("reject", function(){
specify("it should exist", function(){
assert(Promise.reject);
});
describe('it rejects', function(){
var reason = 'the reason',
promise = Promise.reject(reason);
promise.then(function(){
assert(false, 'should not fulfill');
}, function(actualReason){
assert.equal(reason, actualReason);
});
});
});
function assertRejection(promise) {
return promise.then(function(){
assert(false, 'expected rejection, but got fulfillment');
}, function(reason){
assert(reason instanceof Error);
});
}
describe('race', function() {
it("should exist", function() {
assert(Promise.race);
});
it("throws when not passed an array", function(done) {
var nothing = assertRejection(Promise.race());
var string = assertRejection(Promise.race(''));
var object = assertRejection(Promise.race({}));
Promise.all([
nothing,
string,
object
]).then(function(){ done(); });
});
specify('fulfilled after one of the other promises are fulfilled', function(done) {
var firstResolved, secondResolved, firstResolver, secondResolver;
var first = new Promise(function(resolve) {
firstResolver = resolve;
});
first.then(function() {
firstResolved = true;
});
var second = new Promise(function(resolve) {
secondResolver = resolve;
});
second.then(function() {
secondResolved = true;
});
setTimeout(function() {
firstResolver(true);
}, 100);
setTimeout(function() {
secondResolver(true);
}, 0);
Promise.race([first, second]).then(function() {
assert(secondResolved);
assert.equal(firstResolved, undefined);
done();
});
});
specify('the race begins on nextTurn and prioritized by array entry', function(done) {
var firstResolver, secondResolver, nonPromise = 5;
var first = new Promise(function(resolve, reject) {
resolve(true);
});
var second = new Promise(function(resolve, reject) {
resolve(false);
});
Promise.race([first, second, nonPromise]).then(function(value) {
assert.equal(value, true);
done();
});
});
specify('rejected as soon as a promise is rejected', function(done) {
var firstResolver, secondResolver;
var first = new Promise(function(resolve, reject) {
firstResolver = { resolve: resolve, reject: reject };
});
var second = new Promise(function(resolve, reject) {
secondResolver = { resolve: resolve, reject: reject };
});
setTimeout(function() {
firstResolver.reject({});
}, 0);
var firstWasRejected, secondCompleted;
first.catch(function(){
firstWasRejected = true;
});
second.then(function(){
secondCompleted = true;
}, function() {
secondCompleted = true;
});
Promise.race([first, second]).then(function() {
assert(false);
}, function() {
assert(firstWasRejected);
assert(!secondCompleted);
done();
});
});
specify('resolves an empty array to forever pending Promise', function(done) {
var foreverPendingPromise = Promise.race([]),
wasSettled = false;
foreverPendingPromise.then(function() {
wasSettled = true;
}, function() {
wasSettled = true;
});
setTimeout(function() {
assert(!wasSettled);
done();
}, 50);
});
specify('works with a mix of promises and thenables', function(done) {
var promise = new Promise(function(resolve) { setTimeout(function() { resolve(1); }, 10); }),
syncThenable = { then: function (onFulfilled) { onFulfilled(2); } };
Promise.race([promise, syncThenable]).then(function(result) {
assert(result, 2);
done();
});
});
specify('works with a mix of thenables and non-promises', function (done) {
var asyncThenable = { then: function (onFulfilled) { setTimeout(function() { onFulfilled(3); }, 0); } },
nonPromise = 4;
Promise.race([asyncThenable, nonPromise]).then(function(result) {
assert(result, 4);
done();
});
});
});
describe("resolve", function(){
specify("it should exist", function(){
assert(Promise.resolve);
});
describe("1. If x is a promise, adopt its state ", function(){
specify("1.1 If x is pending, promise must remain pending until x is fulfilled or rejected.", function(done){
var expectedValue, resolver, thenable, wrapped;
expectedValue = 'the value';
thenable = {
then: function(resolve, reject){
resolver = resolve;
}
};
wrapped = Promise.resolve(thenable);
wrapped.then(function(value){
assert(value === expectedValue);
done();
});
setTimeout(function(){
resolver(expectedValue);
}, 10);
});
specify("1.2 If/when x is fulfilled, fulfill promise with the same value.", function(done){
var expectedValue, thenable, wrapped;
expectedValue = 'the value';
thenable = {
then: function(resolve, reject){
resolve(expectedValue);
}
};
wrapped = Promise.resolve(thenable);
wrapped.then(function(value){
assert(value === expectedValue);
done();
})
});
specify("1.3 If/when x is rejected, reject promise with the same reason.", function(done){
var expectedError, thenable, wrapped;
expectedError = new Error();
thenable = {
then: function(resolve, reject){
reject(expectedError);
}
};
wrapped = Promise.resolve(thenable);
wrapped.then(null, function(error){
assert(error === expectedError);
done();
});
});
});
describe("2. Otherwise, if x is an object or function,", function(){
specify("2.1 Let then x.then", function(done){
var accessCount, resolver, wrapped, thenable;
accessCount = 0;
thenable = { };
// we likely don't need to test this, if the browser doesn't support it
if (typeof Object.defineProperty !== "function") { done(); return; }
Object.defineProperty(thenable, 'then', {
get: function(){
accessCount++;
if (accessCount > 1) {
throw new Error();
}
return function(){ };
}
});
assert(accessCount === 0);
wrapped = Promise.resolve(thenable);
assert(accessCount === 1);
done();
});
specify("2.2 If retrieving the property x.then results in a thrown exception e, reject promise with e as the reason.", function(done){
var wrapped, thenable, expectedError;
expectedError = new Error();
thenable = { };
// we likely don't need to test this, if the browser doesn't support it
if (typeof Object.defineProperty !== "function") { done(); return; }
Object.defineProperty(thenable, 'then', {
get: function(){
throw expectedError;
}
});
wrapped = Promise.resolve(thenable);
wrapped.then(null, function(error){
assert(error === expectedError, 'incorrect exception was thrown');
done();
});
});
describe('2.3. If then is a function, call it with x as this, first argument resolvePromise, and second argument rejectPromise, where', function(){
specify('2.3.1 If/when resolvePromise is called with a value y, run Resolve(promise, y)', function(done){
var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis;
thenable = {
then: function(resolve, reject){
calledThis = this;
resolver = resolve;
rejector = reject;
}
};
expectedSuccess = 'success';
wrapped = Promise.resolve(thenable);
wrapped.then(function(success){
assert(calledThis === thenable, 'this must be the thenable');
assert(success === expectedSuccess, 'rejected promise with x');
done();
});
setTimeout(function() {
resolver(expectedSuccess);
}, 20);
});
specify('2.3.2 If/when rejectPromise is called with a reason r, reject promise with r.', function(done){
var expectedError, resolver, rejector, thenable, wrapped, calledThis;
thenable = {
then: function(resolve, reject){
calledThis = this;
resolver = resolve;
rejector = reject;
}
};
expectedError = new Error();
wrapped = Promise.resolve(thenable);
wrapped.then(null, function(error){
assert(error === expectedError, 'rejected promise with x');
done();
});
setTimeout(function() {
rejector(expectedError);
}, 20);
});
specify("2.3.3 If both resolvePromise and rejectPromise are called, or multiple calls to the same argument are made, the first call takes precedence, and any further calls are ignored", function(done){
var expectedError, expectedSuccess, resolver, rejector, thenable, wrapped, calledThis,
calledRejected, calledResolved;
calledRejected = 0;
calledResolved = 0;
thenable = {
then: function(resolve, reject){
calledThis = this;
resolver = resolve;
rejector = reject;
}
};
expectedError = new Error();
wrapped = Promise.resolve(thenable);
wrapped.then(function(){
calledResolved++;
}, function(error){
calledRejected++;
assert(calledResolved === 0, 'never resolved');
assert(calledRejected === 1, 'rejected only once');
assert(error === expectedError, 'rejected promise with x');
});
setTimeout(function() {
rejector(expectedError);
rejector(expectedError);
rejector('foo');
resolver('bar');
resolver('baz');
}, 20);
setTimeout(function(){
assert(calledRejected === 1, 'only rejected once');
assert(calledResolved === 0, 'never resolved');
done();
}, 50);
});
describe("2.3.4 If calling then throws an exception e", function(){
specify("2.3.4.1 If resolvePromise or rejectPromise have been called, ignore it.", function(done){
var expectedSuccess, resolver, rejector, thenable, wrapped, calledThis,
calledRejected, calledResolved;
expectedSuccess = 'success';
thenable = {
then: function(resolve, reject){
resolve(expectedSuccess);
throw expectedError;
}
};
wrapped = Promise.resolve(thenable);
wrapped.then(function(success){
assert(success === expectedSuccess, 'resolved not errored');
done();
});
});
specify("2.3.4.2 Otherwise, reject promise with e as the reason.", function(done) {
var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount;
expectedError = new Error();
callCount = 0;
thenable = { then: function() { throw expectedError; } };
wrapped = Promise.resolve(thenable);
wrapped.then(null, function(error){
callCount++;
assert(expectedError === error, 'expected the correct error to be rejected');
done();
});
assert(callCount === 0, 'expected async, was sync');
});
});
});
specify("2.4 If then is not a function, fulfill promise with x", function(done){
var expectedError, resolver, rejector, thenable, wrapped, calledThis, callCount;
thenable = { then: 3 };
callCount = 0;
wrapped = Promise.resolve(thenable);
wrapped.then(function(success){
callCount++;
assert(thenable === success, 'fulfilled promise with x');
done();
});
assert(callCount === 0, 'expected async, was sync');
});
});
describe("3. If x is not an object or function, ", function(){
specify("fulfill promise with x.", function(done){
var thenable, callCount, wrapped;
thenable = null;
callCount = 0;
wrapped = Promise.resolve(thenable);
wrapped.then(function(success){
callCount++;
assert(success === thenable, 'fulfilled promise with x');
done();
}, function(a){
assert(false, 'should not also reject');
});
assert(callCount === 0, 'expected async, was sync');
});
});
});
if (typeof Worker !== 'undefined' && navigator.userAgent.indexOf('PhantomJS') < 1) {
describe('web worker', function () {
it('should work', function (done) {
this.timeout(2000);
var worker = new Worker('./worker.js');
worker.addEventListener('error', function(reason) {
done(new Error("Test failed:" + reason));
});
worker.addEventListener('message', function (e) {
worker.terminate();
assert.equal(e.data, 'pong');
done();
});
worker.postMessage('ping');
});
});
}
});
// thanks to @wizardwerdna for the test case -> https://github.com/tildeio/rsvp.js/issues/66
// Only run these tests in node (phantomjs cannot handle them)
if (typeof module !== 'undefined' && module.exports) {
describe("using reduce to sum integers using promises", function(){
it("should build the promise pipeline without error", function(){
var array, iters, pZero, i;
array = [];
iters = 1000;
for (i=1; i<=iters; i++) {
array.push(i);
}
pZero = Promise.resolve(0);
array.reduce(function(promise, nextVal) {
return promise.then(function(currentVal) {
return Promise.resolve(currentVal + nextVal);
});
}, pZero);
});
it("should get correct answer without blowing the nextTick stack", function(done){
var pZero, array, iters, result, i;
pZero = Promise.resolve(0);
array = [];
iters = 1000;
for (i=1; i<=iters; i++) {
array.push(i);
}
result = array.reduce(function(promise, nextVal) {
return promise.then(function(currentVal) {
return Promise.resolve(currentVal + nextVal);
});
}, pZero);
result.then(function(value){
assert.equal(value, (iters*(iters+1)/2));
done();
});
});
});
}
// Kudos to @Octane at https://github.com/getify/native-promise-only/issues/5 for this, and @getify for pinging me.
describe("Thenables should not be able to run code during assimilation", function () {
specify("resolving to a thenable", function () {
var thenCalled = false;
var thenable = {
then: function () {
thenCalled = true;
}
};
Promise.resolve(thenable);
assert.strictEqual(thenCalled, false);
});
specify("resolving to an evil promise", function () {
var thenCalled = false;
var evilPromise = Promise.resolve();
evilPromise.then = function () {
thenCalled = true;
};
Promise.resolve(evilPromise);
assert.strictEqual(thenCalled, false);
});
});
describe('Promise.prototype.finally', function() {
describe("native finally behaviour", function() {
describe("no value is passed in", function() {
it("does not provide a value to the finally code", function(done) {
var fulfillmentValue = 1;
var promise = Promise.resolve(fulfillmentValue);
promise['finally'](function() {
assert.equal(arguments.length, 0);
done();
});
});
it("does not provide a reason to the finally code", function(done) {
var rejectionReason = new Error();
var promise = Promise.reject(rejectionReason);
promise['finally'](function(arg) {
assert.equal(arguments.length, 0);
done();
});
});
});
describe("non-exceptional cases do not affect the result", function(){
it("preserves the original fulfillment value even if the finally callback returns a value", function(done) {
var fulfillmentValue = 1;
var promise = Promise.resolve(fulfillmentValue);
promise['finally'](function() {
return 2;
}).then(function(value) {
assert.equal(fulfillmentValue, value);
done();
});
});
it("preserves the original rejection reason even if the finally callback returns a value", function(done) {
var rejectionReason = new Error();
var promise = Promise.reject(rejectionReason);
promise['finally'](function() {
return 2;
}).then(undefined, function(reason) {
assert.equal(rejectionReason, reason);
done();
});
});
it("preserves the original fulfillment value even if a non-callable callback is given", function(done) {
var fulfillmentValue = 1;
var promise = Promise.resolve(fulfillmentValue);
promise['finally']().then(function(value) {
assert.equal(fulfillmentValue, value);
done();
});
});
it("preserves the original rejection reason even if a non-callable callback is given", function(done) {
var rejectionReason = new Error();
var promise = Promise.reject(rejectionReason);
promise['finally']().then(undefined, function(reason) {
assert.equal(rejectionReason, reason);
done();
});
});
});
describe("exception cases do propogate the failure", function(){
describe("fulfilled promise", function(){
it("propagates changes via throw", function(done) {
var promise = Promise.resolve(1);
var expectedReason = new Error();
promise['finally'](function() {
throw expectedReason;
}).then(undefined, function(reason) {
assert.deepEqual(expectedReason, reason);
done();
});
});
it("propagates changes via returned rejected promise", function(done){
var promise = Promise.resolve(1);
var expectedReason = new Error();
promise['finally'](function() {
return Promise.reject(expectedReason);
}).then(undefined, function(reason) {
assert.deepEqual(expectedReason, reason);
done();
});
});
});
describe("rejected promise", function(){
it("propagates changes via throw", function(done) {
var promise = Promise.reject(1);
var expectedReason = new Error();
promise['finally'](function() {
throw expectedReason;
}).then(undefined, function(reason) {
assert.deepEqual(expectedReason, reason);
done();
});
});
it("propagates changes via returned rejected promise", function(done){
var promise = Promise.reject(1);
var expectedReason = new Error();
promise['finally'](function() {
return Promise.reject(expectedReason);
}).then(undefined, function(reason) {
assert.deepEqual(expectedReason, reason);
done();
});
});
});
});
});
describe("inheritance", function() {
function Subclass (resolver) {
this._promise$constructor(resolver);
}
Subclass.prototype = Object.create(Promise.Promise.prototype);
Subclass.prototype.constructor = Subclass;
Subclass.prototype._promise$constructor = Promise.Promise;
Subclass.resolve = Promise.Promise.resolve;
Subclass.reject = Promise.Promise.reject;
Subclass.all = Promise.Promise.all;
it("preserves correct subclass when chained", function() {
var promise = Subclass.resolve().finally();
assert.ok(promise instanceof Subclass);
assert.equal(promise.constructor, Subclass);
});
it("preserves correct subclass when rejected", function() {
var promise = Subclass.resolve().finally(function() {
throw new Error("OMG");
});
assert.ok(promise instanceof Subclass);
assert.equal(promise.constructor, Subclass);
});
it("preserves correct subclass when someone returns a thenable", function() {
var promise = Subclass.resolve().finally(function() {
return Promise.Promise.resolve(1);
});
assert.ok(promise instanceof Subclass);
assert.equal(promise.constructor, Subclass);
});
});
});
es6-promise-4.2.8/test/index.html 0000664 0000000 0000000 00000001026 13476252164 0016663 0 ustar 00root root 0000000 0000000
rsvp.js Tests
es6-promise-4.2.8/test/index.js 0000664 0000000 0000000 00000000225 13476252164 0016333 0 ustar 00root root 0000000 0000000 require('./test-adapter.js');
require('./scheduler-test.js');
require('./extension-test.js');
require('promises-aplus-tests-phantom/lib/testFiles');
es6-promise-4.2.8/test/scheduler-test.js 0000664 0000000 0000000 00000004144 13476252164 0020163 0 ustar 00root root 0000000 0000000 /*global describe, it, assert */
var g = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : this;
var Promise = g.adapter.Promise;
var assert = require('assert');
describe('scheduler', function() {
afterEach(function() {
// make sure the es6-promise scheduler is restored after each test
Promise._setScheduler(void 0);
});
describe('Promise._setScheduler', function() {
it('should allow overriding the default scheduling mechanism', function(done) {
// Wrapped in a setTimeout() to make sure that the microtask queue is empty
// Otherwise we would have len > 2 and the overriden scheduling mechanism would not
// be used.
// This is required because the test library uses Promise.
setTimeout(function() {
var microtasks = [];
var resolvedWith = null;
Promise._setScheduler(function(fn) {
microtasks.push(fn);
});
Promise.resolve('value').then(function(v) {
resolvedWith = v;
});
assert.equal(resolvedWith, null);
assert.equal(microtasks.length, 1);
while (microtasks.length) {
microtasks.shift()();
}
assert.equal(resolvedWith, 'value');
// restore the original scheduler
Promise._setScheduler(void 0);
done();
});
});
});
describe('Promise._asap', function() {
it('should allow enqueuing microtasks', function(done) {
Promise._asap(function(arg) {
assert.equal(arg, 'arg');
done();
}, 'arg');
});
});
describe('Promise._setAsap', function() {
it('should allow overriding asap', function(done) {
var called = false;
Promise._setAsap(function(fn, arg) {
called = true;
// call the original implementation
Promise._asap(fn, arg);
// restore the original implementation
Promise._setAsap(Promise._asap);
});
Promise.resolve('value').then(function(v) {
resolvedWith = v;
assert.equal(v, 'value');
assert.equal(called, true);
done();
});
});
});
});
es6-promise-4.2.8/test/test-adapter.js 0000664 0000000 0000000 00000001120 13476252164 0017614 0 ustar 00root root 0000000 0000000 var assert = require('assert');
var Promise = require('./es6-promise');
assert(typeof Promise.polyfill === 'function')
assert(typeof Promise.Promise === 'function')
assert(Promise.Promise === Promise)
function defer() {
var deferred = {};
deferred.promise = new Promise(function(resolve, reject) {
deferred.resolve = resolve;
deferred.reject = reject;
});
return deferred;
}
new Function('return this;')().adapter = {
resolved: function(a) { return Promise.resolve(a); },
rejected: function(a) { return Promise.reject(a); },
deferred: defer,
Promise: Promise
};
es6-promise-4.2.8/test/worker.js 0000664 0000000 0000000 00000000556 13476252164 0016544 0 ustar 00root root 0000000 0000000 importScripts('../es6-promise.js');
new ES6Promise.Promise(function(resolve, reject) {
self.onmessage = function (e) {
if (e.data === 'ping') {
resolve('pong');
} else {
reject(new Error('wrong message'));
}
};
}).then(function (result) {
self.postMessage(result);
}, function (err){
setTimeout(function () {
throw err;
});
});
es6-promise-4.2.8/testem.js 0000664 0000000 0000000 00000000601 13476252164 0015544 0 ustar 00root root 0000000 0000000 'use strict';
module.exports = {
test_page: "test/index.html",
parallel: 5,
frameworks: "mocha",
launchers: {
Mocha: {
"command": `./node_modules/.bin/mocha ${process.env.EMBER_CLI_TEST_OUTPUT}/test/browserify.js -R tap`,
"protocol": "tap"
}
},
launch_in_ci: [
"Phantomjs",
"Mocha"
],
launch_in_dev: [
"Phantomjs",
"Mocha"
],
};
es6-promise-4.2.8/vendor/ 0000775 0000000 0000000 00000000000 13476252164 0015205 5 ustar 00root root 0000000 0000000 es6-promise-4.2.8/vendor/loader.js 0000664 0000000 0000000 00000002442 13476252164 0017013 0 ustar 00root root 0000000 0000000 var define, requireModule, require, requirejs;
(function() {
var registry = {}, seen = {};
define = function(name, deps, callback) {
registry[name] = { deps: deps, callback: callback };
};
requirejs = require = requireModule = function(name) {
requirejs._eak_seen = registry;
if (seen[name]) { return seen[name]; }
seen[name] = {};
if (!registry[name]) {
throw new Error("Could not find module " + name);
}
var mod = registry[name],
deps = mod.deps,
callback = mod.callback,
reified = [],
exports;
for (var i=0, l=deps.length; i