Promisifying functions with callbacks

suggest change

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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents