I was recently working on some code in which I wanted to use Promises, but all that I had was callback-centric code. In the past, I have imported libraries such as bluebird for this particular problem, but now that seems like a bit of overkill to get just one function. I'm already using ES6, so I don't need a polyfill in order to use Promises; all that I want is a simple promisify()
function. Importing an entire library for one function is, IMO, wasteful. Besides, it's more fun to write (and therefore understand at a deeper level) your own implementation, so that's what I did.
If you don't care about why this code works, then you can see it in its completed form below. If you are actually curious as to how I came up with it, then read on and I will explain it to you. The finished code is as follows:
/**
* Convert a callback-based function into a promise.
**/
function promisify(fn) {
return function() {
let args = Array.from(arguments);
return new Promise((resolve, reject) => fn(...args, (error, content) => error ? reject(error) : resolve(content)));
};
}