promisify

Problem Statement

Create a function to turn any function into a "promisfied" function.
Any function to be promisified will always have a callback as the last argument.
The callback will always have this signature: function (result) { }

Sample usage

const exampleFn = function (x, y, callback) {};
const promisedFn = promisify(exampleFn);
promisedFn()
    .then(...)
    .then(...)

Solution

function promisify(fn) {
    return function(...args) {
        return new Promise(function (resolve, reject) {
            function cb(result) {
                resolve(result);
            }
            fn.apply(this, [...args, cb]);
        });
    }
}
Show Comments