-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrapper.js
41 lines (34 loc) · 1.05 KB
/
wrapper.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
var async = require('async');
// Wrap async methods inside a promise
function wrapAsyncMethod(fn, ctx) {
return function() {
// Obtain function arguments
var args = [].slice.call(arguments);
// Return a thunkified function that receives a done callback
return new Promise(function(resolve, reject) {
// Add a custom callback to provided args
args.push(function(err, result) {
// Failed?
if (err) {
return reject(err);
}
// Success
resolve(result);
});
// Call original function
fn.apply(ctx, args);
});
};
}
// Wraps an async object with co-friendly functions
function wrapAsync() {
// Traverse async methods
for (var fn in async) {
// Promisify the method
async[fn] = wrapAsyncMethod(async[fn], async);
}
// Return co-friendly async object
return async;
}
// Expose the wrapped object
module.exports = wrapAsync(async);