JavaScript Promises "Promisifying" functions with callbacks

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

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));


Got any JavaScript Question?