Last active
February 21, 2016 00:34
-
-
Save kjvalencik/61f0b13cfb5299747e2d to your computer and use it in GitHub Desktop.
Extended version of built-in v8 promises
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// TODO: Implement `forEach` and `reduce` | |
class P extends Promise { | |
constructor(fn) { | |
super(fn); | |
} | |
tap(fn) { | |
return this.then(res => { | |
return Promise | |
.resolve(fn(res)) | |
.then(() => res); | |
}); | |
} | |
map(fn) { | |
return this.then(res => Promise.all(res.map(fn))); | |
} | |
filter(fn) { | |
return this.then(res => { | |
return Promise | |
.all(res.map(fn)) | |
.then(filters => res.filter((_, i) => filters[i])); | |
}); | |
} | |
} | |
P.promisify = function promisify(fn, ctx) { | |
return function promisifedMethod() { | |
return new P((resolve, reject) => { | |
const args = new Array(arguments.length + 1); | |
args[arguments.length] = function promisifedMethodCallback(err) { | |
if (err) { | |
return reject(err); | |
} | |
if (arguments.length < 3) { | |
return resolve(arguments[1]); | |
} | |
let res = new Array(arguments.length - 1); | |
for (let i = 0; i < res.length; i++) { | |
res[i] = arguments[i + 1]; | |
} | |
return resolve(res); | |
}; | |
for (let i = 0; i < arguments.length; i++) { | |
args[i] = arguments[i]; | |
} | |
fn.apply(ctx, args); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Built quick and untested for personal use. When I use node.js scripts as a replacement for bash scripts I prefer to not rely any dependencies. But, it's handy to have a few of the common
Bluebird
helpers.