-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
79 lines (73 loc) · 2.18 KB
/
index.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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"use strict";
var Promisify = {};
/**
* Promise chain.
* Stops when some promise resolve.
* EXAMPLE:
* var promises = [promiseAPIMethod1, promiseAPIMethod2, promiseAPIMethod3];
* Promisify.firstInChain(promises).then(function(finalResult){
* //do some with result
* }).catch(function(finalError){
* //handle error
* });
* @param {(function(...)Promise)[]} promiseMethods
* @param {function|undefined} errHandler
* @returns Promise
*/
Promisify.firstInChain = function (promiseMethods, errHandler) {
return promiseMethods.reduce(function(current, next){
return current.catch(function(err){
(typeof errHandler === "function") && errHandler(err);
return next();
}).then(function(data){
return data;
});
}, Promise.reject("Initial error"));
};
/**
* Promise chain
* @param promiseMethods
* @returns Promise
*/
Promisify.chain = function (promiseMethods) {
return promiseMethods.reduce(function (current, next) {
return current.then(next);
}, Promise.resolve());
};
/**
* Promise chain, TURN DOWN FOR WHAT
* @param promiseMethods
* @returns Promise
*/
Promisify.chainForce = function (promiseMethods) {
return promiseMethods.reduce(function (current, next) {
return current.catch(function (err) {
return next(err);
}).then(function () {
return next.apply(next, arguments);
});
}, Promise.resolve());
};
/**
* Defer method calls.
*
* @param {Object} instance
* @param {Promise} ready
* @param {string[]}methods
*/
Promisify.defer = function(instance, ready, methods) {
methods.forEach(function (method) {
if (instance[method] && !instance.hasOwnProperty(method)) {
instance[method] = function () {
var args = arguments;
ready.then(function () {
methods.forEach(function (method) {
delete instance[method];
});
instance[method].apply(instance, args);
});
};
}
});
};
module.exports = Promisify;