Skip to content

Instantly share code, notes, and snippets.

@getify
Created February 14, 2019 20:55
Show Gist options
  • Save getify/1398f3ce0705ceff1ffb6bb757169ab9 to your computer and use it in GitHub Desktop.
Save getify/1398f3ce0705ceff1ffb6bb757169ab9 to your computer and use it in GitHub Desktop.
thenify()... turn an err-first callback into two functions that can suitably be passed to a promise.then(..) and/or .catch(..)
function somethingThatReturnsAPromise(x,y,z) { .. }
function myCallback(err,v) {
if (err) {
console.error(err);
}
else {
console.log(v);
}
}
// **************
somethingThatReturnsAPromise(1,2,3)
.then( ...thenify(myCallback) );
somethingThatReturnsAPromise(4,5,6)
.then( thenify(myCallback)[0] )
.catch( thenify(myCallback)[1] );
var [tf,cf] = thenify(myCallback);
somethingThatReturnsAPromise(7,8,9)
.then(tf)
.catch(cf);
function thenify(errFirstCB) {
return [
function tf(v) {
errFirstCB.call(this,undefined,v);
},
function cf(e) {
errFirstCB.call(this,e);
}
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment