JavaScript "Promisifying" functions with callbacks


Example

Given a function that accepts a Node-style callback,

fooFn(options, function callback(err, result) { ... });

you can promisify it (convert it to a promise-based function) like this:

function promiseFooFn(options) {
    return new Promise((resolve, reject) =>
        fooFn(options, (err, result) =>
            // If there's an error, reject; otherwise resolve
            err ? reject(err) : resolve(result)
        )
    );
}

This function can then be used as follows:

promiseFooFn(options).then(result => {
    // success!
}).catch(err => {
    // error!
});

In a more generic way, here's how to promisify any given callback-style function:

function promisify(func) {
    return function(...args) {
        return new Promise((resolve, reject) => {
            func(...args, (err, result) => err ? reject(err) : resolve(result));
        });
    }
}

This can be used like this:

const fs = require('fs');
const promisedStat = promisify(fs.stat.bind(fs));

promisedStat('/foo/bar')
    .then(stat => console.log('STATE', stat))
    .catch(err => console.log('ERROR', err));