Skip to content

Instantly share code, notes, and snippets.

@kjvalencik
Last active February 21, 2016 00:34
Show Gist options
  • Save kjvalencik/61f0b13cfb5299747e2d to your computer and use it in GitHub Desktop.
Save kjvalencik/61f0b13cfb5299747e2d to your computer and use it in GitHub Desktop.
Extended version of built-in v8 promises
// 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);
});
};
};
@kjvalencik
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment