forked from duzun/promise-sugar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
promise-sugar.js
62 lines (53 loc) · 2.14 KB
/
promise-sugar.js
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
55
56
57
58
59
60
61
62
/**
* Promise syncatctic sugar - no need to write ".then"
*
* @license MIT
* @version 1.0.1
* @git https://github.com/duzun/promise-sugar
* @umd AMD, Browser, CommonJs
* @author DUzun.Me
*/
/*global Promise */
;(function (name, global) {
var undefined
, UNDEFINED = undefined + NIL
;
(typeof define != 'function' || !define.amd
? typeof module != UNDEFINED && module.exports
? function (deps, factory) { module.exports = factory(); } // CommonJs
: function (deps, factory) { global[name] = factory(); } // Browser
: define // AMD
)
/*define*/([], function factory() {
// -------------------------------------------------------------
function sweeten(p) {
// new Promise(p) - [[Construct]]
if ( typeof p == 'function' ) {
return sweeten(new Promise(p));
}
// Make sure p is a thenable
if ( !(p && p.then && typeof p.then === 'function') ) {
p = Promise.resolve(p);
}
then.then = then;
// then.__proto__ = Promise.prototype; // not sure this is a good idea
// an alternative to setting then.__proto__:
then.constructor = Promise;
then.catch = Promise.prototype.catch; // some sugar
// then.catch = function (reject) { return this.then(undefined, reject); }
return then;
function then(onResolve, onReject) {
return sweeten(p.then(onResolve, onReject));
}
}
// -------------------------------------------------------------
// Some more sugar:
sweeten.resolve = function (val) { return sweeten(Promise.resolve(val)); };
sweeten.reject = function (val) { return sweeten(Promise.reject(val)); };
sweeten.all = function (val) { return sweeten(Promise.all(val)); };
sweeten.race = function (val) { return sweeten(Promise.race(val)); };
// -------------------------------------------------------------
return sweeten;
});
}
('sweeten', typeof global == 'undefined' ? this : global));