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:


Promises:
* Syntax
* Promisifying functions with callbacks

Table Of Contents
11 Arrays
12 Objects
14 Classes
16 Map
17 Set
24 Loops
27 Date
29 Scope
30 AJAX
31 Promises
35 Cookies
41 JSON
44 Fetch
45 Modules
46 Screen
64 Console
68 Symbols
73 Modals
76 Events
86 Proxy
89 WeakMap
90 WeakSet
102 Tilde