-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjquery-promise.es6
More file actions
54 lines (44 loc) · 1.46 KB
/
jquery-promise.es6
File metadata and controls
54 lines (44 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
/**
* Miniature ES6 Promise polyfill based on jQuery.Deferred.
*
* jQuery 3 is Promises/A+ compliant, so this should be good enough for
* most situations in which jQuery is being imported anyway.
*/
import { Deferred, when, each } from 'jquery';
function finallyImp(callback) {
return this.then(callback, callback);
}
function toPromise(deferred, target) {
const promise = deferred.promise(target);
promise.finally = finallyImp;
return promise;
}
export default function Promise(executor) {
const deferred = Deferred();
const resolve = deferred.resolve.bind(deferred),
reject = deferred.reject.bind(deferred);
executor(resolve, reject);
return toPromise(deferred);
}
Promise.all = function(iterable) {
return toPromise(when.apply(null, iterable));
}
Promise.race = function(iterable) {
const deferred = Deferred();
function resolved(value) {
if (deferred.state() === 'pending') deferred.resolve(value);
}
function rejected(reason) {
if (deferred.state() === 'pending') deferred.reject(reason);
}
each(iterable, (key, promise) => promise.then(resolved, rejected));
return toPromise(deferred);
}
Promise.resolve = function(value) {
return toPromise(Deferred().resolve(value));
}
Promise.reject = function(reason) {
return toPromise(Deferred().reject(reason));
}
const local = global || self || window || Function('return this')();
if (local && !local.Promise) local.Promise = Promise;