Last active
June 23, 2017 01:32
-
-
Save santiq/19a9d5ae6fcf12af6e441dc97fdf53b5 to your computer and use it in GitHub Desktop.
Promisify a function with callback
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
// Needs ... notation to be available | |
const promisify = (fn) => { | |
return (...args) => { | |
return new Promise((resolve, reject)=>{ | |
fn(...args, function(err, res){ | |
if(err){ | |
return reject(err); | |
} | |
return resolve(res); | |
}) | |
}) | |
} | |
} | |
// Polified version | |
"use strict"; | |
var promisify = function promisify(fn) { | |
return function () { | |
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { | |
args[_key] = arguments[_key]; | |
} | |
return new Promise(function (resolve, reject) { | |
fn.apply(undefined, args.concat([function (err, res) { | |
if (err) { | |
return reject(err); | |
} | |
return resolve(res); | |
}])); | |
}); | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment