By Benjamin Gruenbaum


2014-03-19 22:47:26 8 Comments

I want to work with promises but I have a callback API in a format like:

1. DOM load or other one time event:

window.onload; // set to callback
...
window.onload = function() {

};

2. Plain callback:

function request(onChangeHandler) {
    ...
}
request(function() {
    // change happened
    ...
});

3. Node style callback ("nodeback"):

function getStuff(dat, callback) {
    ...
}
getStuff("dataParam", function(err, data) {
    ...
})

4. A whole library with node style callbacks:

API;
API.one(function(err, data) {
    API.two(function(err, data2) {
        API.three(function(err, data3) {
            ...
        });
    });
});

How do I work with the API in promises, how do I "promisify" it?

20 comments

@Benjamin Gruenbaum 2014-03-19 22:47:26

Promises have state, they start as pending and can settle to:

  • fulfilled meaning that the computation completed successfully.
  • rejected meaning that the computation failed.

Promise returning functions should never throw, they should return rejections instead. Throwing from a promise returning function will force you to use both a } catch { and a .catch. People using promisified APIs do not expect promises to throw. If you're not sure how async APIs work in JS - please see this answer first.

1. DOM load or other one time event:

So, creating promises generally means specifying when they settle - that means when they move to the fulfilled or rejected phase to indicate the data is available (and can be accessed with .then).

With modern promise implementations that support the Promise constructor like native ES6 promises:

function load() {
    return new Promise(function(resolve, reject) {
        window.onload = resolve;
    });
}

You would then use the resulting promise like so:

load().then(function() {
    // Do things after onload
});

With libraries that support deferred (Let's use $q for this example here, but we'll also use jQuery later):

function load() {
    var d = $q.defer();
    window.onload = function() { d.resolve(); };
    return d.promise;
}

Or with a jQuery like API, hooking on an event happening once:

function done() {
    var d = $.Deferred();
    $("#myObject").once("click",function() {
        d.resolve();
    });
    return d.promise();
}

2. Plain callback:

These APIs are rather common since well… callbacks are common in JS. Let's look at the common case of having onSuccess and onFail:

function getUserData(userId, onLoad, onFail) { …

With modern promise implementations that support the Promise constructor like native ES6 promises:

function getUserDataAsync(userId) {
    return new Promise(function(resolve, reject) {
        getUserData(userId, resolve, reject);
    });
}

With libraries that support deferred (Let's use jQuery for this example here, but we've also used $q above):

function getUserDataAsync(userId) {
    var d = $.Deferred();
    getUserData(userId, function(res){ d.resolve(res); }, function(err){ d.reject(err); });
    return d.promise();
}

jQuery also offers a $.Deferred(fn) form, which has the advantage of allowing us to write an expression that emulates very closely the new Promise(fn) form, as follows:

function getUserDataAsync(userId) {
    return $.Deferred(function(dfrd) {
        getUserData(userId, dfrd.resolve, dfrd.reject);
    }).promise();
}

Note: Here we exploit the fact that a jQuery deferred's resolve and reject methods are "detachable"; ie. they are bound to the instance of a jQuery.Deferred(). Not all libs offer this feature.

3. Node style callback ("nodeback"):

Node style callbacks (nodebacks) have a particular format where the callbacks is always the last argument and its first parameter is an error. Let's first promisify one manually:

getStuff("dataParam", function(err, data) { …

To:

function getStuffAsync(param) {
    return new Promise(function(resolve, reject) {
        getStuff(param, function(err, data) {
            if (err !== null) reject(err);
            else resolve(data);
        });
    });
}

With deferreds you can do the following (let's use Q for this example, although Q now supports the new syntax which you should prefer):

function getStuffAsync(param) {
    var d = Q.defer();
    getStuff(param, function(err, data) {
        if (err !== null) d.reject(err);
        else d.resolve(data);
    });
    return d.promise;   
}

In general, you should not promisify things manually too much, most promise libraries that were designed with Node in mind as well as native promises in Node 8+ have a built in method for promisifying nodebacks. For example

var getStuffAsync = Promise.promisify(getStuff); // Bluebird
var getStuffAsync = Q.denodeify(getStuff); // Q
var getStuffAsync = util.promisify(getStuff); // Native promises, node only

4. A whole library with node style callbacks:

There is no golden rule here, you promisify them one by one. However, some promise implementations allow you to do this in bulk, for example in Bluebird, converting a nodeback API to a promise API is as simple as:

Promise.promisifyAll(API);

Or with native promises in Node:

const { promisify } = require('util');
const promiseAPI = Object.entries(API).map(([key, v]) => ({key, fn: promisify(v)}))
                         .reduce((o, p) => Object.assign(o, {[p.key]: p.fn}), {});

Notes:

  • Of course, when you are in a .then handler you do not need to promisify things. Returning a promise from a .then handler will resolve or reject with that promise's value. Throwing from a .then handler is also good practice and will reject the promise - this is the famous promise throw safety.
  • In an actual onload case, you should use addEventListener rather than onX.

@Roamer-1888 2014-04-19 10:43:50

Benjamin, I accepted your invitation to edit and added a further jQuery example to case 2. It will need peer reviewing before it appears. Hope you like it.

@Benjamin Gruenbaum 2014-04-24 09:44:07

@Roamer-1888 it got rejected since I didn't see and accept it in time. For what it's worth I don't think the addition is too relevant although useful.

@Roamer-1888 2014-04-24 19:36:17

Benjamin, whether or not resolve() and reject() are written to be reusable, I venture that my suggested edit is relevant because it offers a jQuery example of the form $.Deferred(fn), which is otherwise lacking. If only one jQuery example is included, then I suggest that it should be of this form rather than var d = $.Deferred(); etc. as people should be encouraged to use the oft neglected $.Deferred(fn) form, plus, in an answer like this, it puts jQuery more on a par with libs that use the Revealing Constructor Pattern.

@Benjamin Gruenbaum 2014-04-24 19:39:47

Heh, to be 100% fair I didn't know jQuery let you do $.Deferred(fn), if you edit that in instead of the existing example in the next 15 minutes I'm sure I can try to approve it on time :)

@Roamer-1888 2014-04-26 10:44:42

Benjamin, sorry I missed your 15 minute deadline but will try to catch you online soon. I'm sort of pleased my earlier edit wasn't accepted as I've had a chance to amend it to something better. It will need to be an addition, not a replacement.

@fraxture 2015-01-15 12:34:30

What are you referring to when you write "modern promise implementation"? What are you including to be able to use the Promise constructor?

@Benjamin Gruenbaum 2015-01-15 12:41:17

@fraxture pretty much every implementation written after the Promises/A+ spec and the consteuctor spec was born or was altered because of it to match it - these are most promises we know : Q, Bluebird, When, RSVP, $q (since 1.3), native promises, jQuery starting with the next version and so on.

@fraxture 2015-01-15 14:07:08

@BenjaminGruenbaum: got ya. But what do I need to include to use the Promise constructor? Installing Q with npm and then requring it did not work...

@Benjamin Gruenbaum 2015-01-15 14:59:53

With Q it's called Q.Promise - the API docs of Q are good and cover this.

@fraxture 2015-01-15 15:01:37

The answer was that I needed to npm install promise --save and then var Promise = require('promise') in order to be able to new Promise.

@Benjamin Gruenbaum 2015-01-15 16:29:53

Don't use that library - use Bluebied instead.

@velop 2016-04-18 15:17:05

What happens if my onX event can happen multiple times. Can this also promisified?

@Benjamin Gruenbaum 2016-04-18 18:24:42

No, if a callback happens multiple times it should not be promisified, promises are for one time things. For things that happen multiple times the easiest thing would be to use an event emitter - more advanced patterns like async iterators (iterators of promises) or observables (push object streams) exist. Promises are only for one time things.

@user1164937 2016-08-08 00:37:08

I have a question about number 3 with nested callbacks. How come I can't simply call reject/resolve? It seems that at least in my case, I have to return them.

@Akansh Gulati 2016-09-01 12:06:03

@BenjaminGruenbaum I want to ask regarding the 3rd heading promisify method, though it converts a callback to promise but is it possible to handle error exactly where I am making it a promise?

@hitautodestruct 2016-11-15 04:27:57

It seems that this answer included everything except the actual usage of a promisified function. I added an example of the load functions use after it was promisified.

@Bruno 2017-05-16 05:27:14

This is a great answer. You may want to update it by mentioning also util.promisify, that Node.js is going to add to its core starting from RC 8.0.0. Its working it's not much different from Bluebird Promise.promisify, but has the advantage of not requiring additional dependencies, in case you just want native Promise. I've written a blog post about util.promisify for anyone who want read more on the topic.

@robe007 2018-06-18 17:30:06

@BenjaminGruenbaum A few days ago, I sent an edit propose to you last code: const promiseAPI = Object.keys(API).map(key => {return {key, fn:util.promisify(API[key])} }).reduce((o, p) => Object.assign(o, {[p.key] : p.fn}), {}); Why did you rejected?

@Benjamin Gruenbaum 2018-06-18 17:31:49

@robe007 probably just butter fingers - sorry! I edited it in now.

@robe007 2018-06-18 17:37:50

@BenjaminGruenbaum Please, see it again, your code still wrong. Look on my edit proposal few days ago.

@Benjamin Gruenbaum 2018-06-18 17:59:43

@robe007 I did - I think the way I fixed it works - there are two ways to return objects from arrow functions: either adding a return to the block body x => { return {}} or to mark it as an expression x => ({}) - both are valid and work. Maybe I'm still missing your point?

@robe007 2018-06-18 18:49:42

@BenjaminGruenbaum Yes I know my friend, but you are missing to close the curly bracket in the returned object {key, fn: util.promisify(API[key])} from your map. You see it?

@robe007 2018-06-18 19:37:03

@BenjaminGruenbaum I have sent another edit proposal again to your last modification.

@Mzndako 2019-06-21 10:38:43

Below is the implementation of how a function (callback API) can be converted to a promise.

function promisify(functionToExec) {
  return function() {
    var array = Object.values(arguments);
    return new Promise((resolve, reject) => {
      array.push(resolve)
      try {
         functionToExec.apply(null, array);
      } catch (error) {
         reject(error)
      }
    })
  }
}

// USE SCENARIO

function apiFunction (path, callback) { // Not a promise
  // Logic
}

var promisedFunction = promisify(apiFunction);

promisedFunction('path').then(()=>{
  // Receive the result here (callback)
})

// Or use it with await like this
let result = await promisedFunction('path');

@Jone Polvora 2019-06-20 15:01:52

I've created a generic function that I can reuse.

       const wrapIntoPromise: (fnToExecute) => {
            return new Promise((resolve, reject) => {
                return fnToExecute(resolve, reject);
            });
        }

        //example
        async function run() {
           await wrapIntoPromise((resolve, reject) => { 
               /*execute any function here with callbacks etc
                when done just call return resolve(valueToReturn)
               */ 
               return backup({
                  callback: function() { return resolve()}
               });

           });
        }

@Gian Marco Gherardi 2017-05-31 06:46:50

Node.js 8.0.0 includes a new util.promisify() API that allows standard Node.js callback style APIs to be wrapped in a function that returns a Promise. An example use of util.promisify() is shown below.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

readFile('/some/file')
  .then((data) => { /** ... **/ })
  .catch((err) => { /** ... **/ });

See Improved support for Promises

@Benjamin Gruenbaum 2017-05-31 10:50:49

There are already two answers describing this, why post a third one?

@Gian Marco Gherardi 2017-06-15 09:09:29

Just because that version of node is now released, and I've reported "official" feature description and link.

@Sivashanmugam Kannan 2017-08-11 11:31:02

Before converting a function as promise In Node.JS

var request = require('request'); //http wrapped module

function requestWrapper(url, callback) {
    request.get(url, function (err, response) {
      if (err) {
        callback(err);
      }else{
        callback(null, response);             
      }      
    })
}


requestWrapper(url, function (err, response) {
    console.log(err, response)
})

After Converting It

var request = require('request');

function requestWrapper(url) {
  return new Promise(function (resolve, reject) { //returning promise
    request.get(url, function (err, response) {
      if (err) {
        reject(err); //promise reject
      }else{
        resolve(response); //promise resolve
      }
    })
  })
}


requestWrapper('http://localhost:8080/promise_request/1').then(function(response){
    console.log(response) //resolve callback(success)
}).catch(function(error){
    console.log(error) //reject callback(failure)
})

Incase you need to handle multiple request

var allRequests = [];
allRequests.push(requestWrapper('http://localhost:8080/promise_request/1')) 
allRequests.push(requestWrapper('http://localhost:8080/promise_request/2'))
allRequests.push(requestWrapper('http://localhost:8080/promise_request/5'))    

Promise.all(allRequests).then(function (results) {
  console.log(results);//result will be array which contains each promise response
}).catch(function (err) {
  console.log(err)
});

@Julian Torregrosa 2019-04-04 21:55:37

It is like 5 years late, but I wanted to post here my promesify version which takes functions from callbacks API and turns them into promises

const promesify = fn => {
  return (...params) => ({
    then: cbThen => ({
      catch: cbCatch => {
        fn(...params, cbThen, cbCatch);
      }
    })
  });
};

Take a look to this very simple version here: https://gist.github.com/jdtorregrosas/aeee96dd07558a5d18db1ff02f31e21a

@Benjamin Gruenbaum 2019-04-04 22:02:07

That's not a promise, it doesn't chain, deal with errors thrown in the callback or accept a second parameter in then...

@efkan 2017-01-02 13:19:02

Today, I can use Promise in Node.js as a plain Javascript method.

A simple and basic example to Promise (with KISS way):

Plain Javascript Async API code:

function divisionAPI (number, divider, successCallback, errorCallback) {

    if (divider == 0) {
        return errorCallback( new Error("Division by zero") )
    }

    successCallback( number / divider )

}

Promise Javascript Async API code:

function divisionAPI (number, divider) {

    return new Promise(function (fulfilled, rejected) {

        if (divider == 0) {
            return rejected( new Error("Division by zero") )
        }

        fulfilled( number / divider )

     })

}

(I recommend visiting this beautiful source)

Also Promise can be used with together async\await in ES7 to make the program flow wait for a fullfiled result like the following:

function getName () {

    return new Promise(function (fulfilled, rejected) {

        var name = "John Doe";

        // wait 3000 milliseconds before calling fulfilled() method
        setTimeout ( 
            function() {
                fulfilled( name )
            }, 
            3000
        )

    })

}


async function foo () {

    var name = await getName(); // awaits for a fulfilled result!

    console.log(name); // the console writes "John Doe" after 3000 milliseconds

}


foo() // calling the foo() method to run the code

Another usage with the same code by using .then() method

function getName () {

    return new Promise(function (fulfilled, rejected) {

        var name = "John Doe";

        // wait 3000 milliseconds before calling fulfilled() method
        setTimeout ( 
            function() {
                fulfilled( name )
            }, 
            3000
        )

    })

}


// the console writes "John Doe" after 3000 milliseconds
getName().then(function(name){ console.log(name) })

Promise can also be used on any platform that is based on Node.js like react-native.

Bonus: An hybrid method
(The callback method is assumed to have two parameters as error and result)

function divisionAPI (number, divider, callback) {

    return new Promise(function (fulfilled, rejected) {

        if (divider == 0) {
            let error = new Error("Division by zero")
            callback && callback( error )
            return rejected( error )
        }

        let result = number / divider
        callback && callback( null, result )
        fulfilled( result )

     })

}

The above method can respond result for old fashion callback and Promise usages.

Hope this helps.

@Dmitri Zaitsev 2018-04-18 09:55:51

These do not seem to show how to convert to promises.

@onmyway133 2018-10-09 13:35:18

You can do something like this

// @flow

const toPromise = (f: (any) => void) => {
  return new Promise<any>((resolve, reject) => {
    try {
      f((result) => {
        resolve(result)
      })
    } catch (e) {
      reject(e)
    }
  })
}

export default toPromise

Then use it

async loadData() {
  const friends = await toPromise(FriendsManager.loadFriends)

  console.log(friends)
}

@Benjamin Gruenbaum 2018-10-09 15:52:18

Hey, I'm not sure what this adds to existing answers (maybe clarify?). Also, there is no need for the try/catch inside the promise constructor (it does this automatically for you). It's also unclear what functions this works for (that call the callback with a single argument on success? How are errors handled?)

@loretoparisi 2017-11-29 23:34:06

My promisify version of a callback function is the P function:

var P = function() {
  var self = this;
  var method = arguments[0];
  var params = Array.prototype.slice.call(arguments, 1);
  return new Promise((resolve, reject) => {
    if (method && typeof(method) == 'function') {
      params.push(function(err, state) {
        if (!err) return resolve(state)
        else return reject(err);
      });
      method.apply(self, params);
    } else return reject(new Error('not a function'));
  });
}
var callback = function(par, callback) {
  var rnd = Math.floor(Math.random() * 2) + 1;
  return rnd > 1 ? callback(null, par) : callback(new Error("trap"));
}

callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback", (err, state) => err ? console.error(err) : console.log(state))
callback("callback", (err, state) => err ? console.error(err) : console.log(state))

P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))
P(callback, "promise").then(v => console.log(v)).catch(e => console.error(e))

The P function requires that the callback signature must be callback(error,result).

@Benjamin Gruenbaum 2017-11-30 10:58:21

What advantage does this have over native promisify or over the answers above?

@loretoparisi 2017-11-30 11:25:57

What do you mean for native promisify?

@Benjamin Gruenbaum 2017-11-30 12:38:28

@loretoparisi 2017-11-30 13:35:34

ah yes of course :). Just and example to show the basic idea. In fact you can see how even the native one requires that the function signature must some defined like (err, value) => ... or you must define a custom one (see Custom promisified functions). Thank you good catcha.

@Patrick Roberts 2019-05-10 17:37:26

@loretoparisi FYI, var P = function (fn, ...args) { return new Promise((resolve, reject) => fn.call(this, ...args, (error, result) => error ? reject(error) : resolve(result))); }; would do the same thing as yours and it's a lot simpler.

@Pujan Srivastava 2017-10-17 23:56:27

es6-promisify converts callback-based functions to Promise-based functions.

const promisify = require('es6-promisify');

const promisedFn = promisify(callbackedFn, args);

Ref: https://www.npmjs.com/package/es6-promisify

@Do Async 2017-10-12 22:19:07

In Node.js 8 you can promisify object methods on the fly using this npm module:

https://www.npmjs.com/package/doasync

It uses util.promisify and Proxies so that your objects stay unchanged. Memoization is also done with the use of WeakMaps). Here are some examples:

With objects:

const fs = require('fs');
const doAsync = require('doasync');

doAsync(fs).readFile('package.json', 'utf8')
  .then(result => {
    console.dir(JSON.parse(result), {colors: true});
  });

With functions:

doAsync(request)('http://www.google.com')
  .then(({body}) => {
    console.log(body);
    // ...
  });

You can even use native call and apply to bind some context:

doAsync(myFunc).apply(context, params)
  .then(result => { /*...*/ });

@jituanlin 2017-07-30 13:39:26

The callback style function always like this(almost all function in node.js is this style):

//fs.readdir(path[, options], callback)
fs.readdir('mypath',(err,files)=>console.log(files))

This style has same feature:

  1. the callback function is passed by last argument.

  2. the callback function always accept the error object as it's first argument.

So, you could write a function for convert a function with this style like this:

const R =require('ramda')

/**
 * A convenient function for handle error in callback function.
 * Accept two function res(resolve) and rej(reject) ,
 * return a wrap function that accept a list arguments,
 * the first argument as error, if error is null,
 * the res function will call,else the rej function.
 * @param {function} res the function which will call when no error throw
 * @param {function} rej the function which will call when  error occur
 * @return {function} return a function that accept a list arguments,
 * the first argument as error, if error is null, the res function
 * will call,else the rej function
 **/
const checkErr = (res, rej) => (err, ...data) => R.ifElse(
    R.propEq('err', null),
    R.compose(
        res,
        R.prop('data')
    ),
    R.compose(
        rej,
        R.prop('err')
    )
)({err, data})

/**
 * wrap the callback style function to Promise style function,
 * the callback style function must restrict by convention:
 * 1. the function must put the callback function where the last of arguments,
 * such as (arg1,arg2,arg3,arg...,callback)
 * 2. the callback function must call as callback(err,arg1,arg2,arg...)
 * @param {function} fun the callback style function to transform
 * @return {function} return the new function that will return a Promise,
 * while the origin function throw a error, the Promise will be Promise.reject(error),
 * while the origin function work fine, the Promise will be Promise.resolve(args: array),
 * the args is which callback function accept
 * */
 const toPromise = (fun) => (...args) => new Promise(
    (res, rej) => R.apply(
        fun,
        R.append(
            checkErr(res, rej),
            args
        )
    )
)

For more concise, above example used ramda.js. Ramda.js is a excellent library for functional programming. In above code, we used it's apply(like javascript function.prototype.apply) and append(like javascript function.prototype.push ). So, we could convert the a callback style function to promise style function now:

const {readdir} = require('fs')
const readdirP = toPromise(readdir)
readdir(Path)
    .then(
        (files) => console.log(files),
        (err) => console.log(err)
    )

toPromise and checkErr function is own by berserk library, it's a functional programming library fork by ramda.js(create by me).

Hope this answer is useful for you.

@Bruno 2017-05-16 05:35:57

In release candidate for Node.js 8.0.0, there's a new utility, util.promisify (I've written about util.promisify), that encapsulates the capacity of promisifying whatever function.

It is not much different from the approaches suggested in the other answers, but has the advantage of being a core method, and not requiring additional dependencies.

const fs = require('fs');
const util = require('util');

const readFile = util.promisify(fs.readFile);

Then you've a readFile method that returns a native Promise.

readFile('./notes.txt')
  .then(txt => console.log(txt))
  .catch(...);

@Benjamin Gruenbaum 2017-05-16 12:53:47

Hey, I (OP) actually suggested util.promisify twice (back in 2014 when this question was written, and a few months ago - which I pushed for as a core member of Node and is the current version we have in Node). Since it is not yet publicly available - I did not add it to this answer yet. We would deeply appreciate usage feedback though and getting to know what some pitfalls are in order to have better docs for the release :)

@Benjamin Gruenbaum 2017-05-16 12:55:53

In addition, you might want to discuss the custom flag for promisifying with util.promisify in your blog post :)

@Bruno 2017-05-16 16:23:47

@BenjaminGruenbaum Do you mean the fact that using the util.promisify.custom symbol it is possible to override the result of util.promisify? To be honest this was an intentional miss, cause I'm not yet able to find a useful use case. Perhaps you can give me some inputs?

@Benjamin Gruenbaum 2017-05-16 19:05:30

Sure, consider APIs like fs.exists or APIs that do not follow the Node convention - a bluebird Promise.promisify would get them wrong, but util.promisify gets them right.

@Paul Spaulding 2017-04-12 16:48:09

Under node v7.6+ which has built in promises and async:

// promisify.js
let promisify = fn => (...args) =>
    new Promise((resolve, reject) =>
        fn(...args, (err, result) => {
            if (err) return reject(err);
            return resolve(result);
        })
    );

module.exports = promisify;

How to use:

let readdir = require('fs').readdir;
let promisify = require('./promisify');
let readdirP = promisify(readdir);

async function myAsyncFn(path) {
    let entries = await readdirP(path);
    return entries;
}

@Nicolas Zozol 2017-01-22 13:22:52

You can use native Promise in ES6, for exemple dealing with setTimeout:

enqueue(data) {

    const queue = this;
    // returns the Promise
    return new Promise(function (resolve, reject) {
        setTimeout(()=> {
                queue.source.push(data);
                resolve(queue); //call native resolve when finish
            }
            , 10); // resolve() will be called in 10 ms
    });

}

In this exemple, the Promise has no reason to fail, so reject() is never called.

@daviddavis 2016-11-28 03:07:12

With plain old vanilla javaScript, here's a solution to promisify an api callback.

function get(url, callback) {
        var xhr = new XMLHttpRequest();
        xhr.open('get', url);
        xhr.addEventListener('readystatechange', function () {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    console.log('successful ... should call callback ... ');
                    callback(null, JSON.parse(xhr.responseText));
                } else {
                    console.log('error ... callback with error data ... ');
                    callback(xhr, null);
                }
            }
        });
        xhr.send();
    }

/**
     * @function promisify: convert api based callbacks to promises
     * @description takes in a factory function and promisifies it
     * @params {function} input function to promisify
     * @params {array} an array of inputs to the function to be promisified
     * @return {function} promisified function
     * */
    function promisify(fn) {
        return function () {
            var args = Array.prototype.slice.call(arguments);
            return new Promise(function(resolve, reject) {
                fn.apply(null, args.concat(function (err, result) {
                    if (err) reject(err);
                    else resolve(result);
                }));
            });
        }
    }

var get_promisified = promisify(get);
var promise = get_promisified('some_url');
promise.then(function (data) {
        // corresponds to the resolve function
        console.log('successful operation: ', data);
}, function (error) {
        console.log(error);
});

@user1852503 2016-08-04 00:45:36

When you have a few functions that take a callback and you want them to return a promise instead you can use this function to do the conversion.

function callbackToPromise(func){

    return function(){

        // change this to use what ever promise lib you are using
        // In this case i'm using angular $q that I exposed on a util module

        var defered = util.$q.defer();

        var cb = (val) => {
            defered.resolve(val);
        }

        var args = Array.prototype.slice.call(arguments);
        args.push(cb);    
        func.apply(this, args);

        return defered.promise;
    }
}

@Apoorv 2016-06-20 13:38:56

You can use JavaScript native promises with Node JS.

My Cloud 9 code link: https://ide.c9.io/adx2803/native-promises-in-node

/**
* Created by dixit-lab on 20/6/16.
*/

var express = require('express');
var request = require('request');   //Simplified HTTP request client.


var app = express();

function promisify(url) {
    return new Promise(function (resolve, reject) {
        request.get(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            }
            else {
                reject(error);
            }
        })
    });
}

//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
    //get the post with post id 100
    promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
        var obj = JSON.parse(result);
        return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
    })
    .catch(function (e) {
        console.log(e);
    })
    .then(function (result) {
        res.end(result);
    })
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("Example app listening at http://%s:%s", host, port)
})

//run webservice on browser : http://localhost:8081/listAlbums

@Jason Loveman 2015-04-07 18:30:14

The Q library by kriskowal includes callback-to-promise functions. A method like this:

obj.prototype.dosomething(params, cb) {
  ...blah blah...
  cb(error, results);
}

can be converted with Q.ninvoke

Q.ninvoke(obj,"dosomething",params).
then(function(results) {
});

@Bergi 2015-04-07 20:03:37

The canonical answer already mentions Q.denodeify. Do we need to emphasize library helpers?

@Ed Sykes 2015-12-28 14:34:40

i found this useful as a google about promisifying in Q leads here

@Leo 2015-01-14 04:15:27

I don't think the window.onload suggestion by @Benjamin will work all the time, as it doesn't detect whether it is called after the load. I have been bitten by that many times. Here is a version which should always work:

function promiseDOMready() {
    return new Promise(function(resolve) {
        if (document.readyState === "complete") return resolve();
        document.addEventListener("DOMContentLoaded", resolve);
    });
}
promiseDOMready().then(initOnLoad);

@Alnitak 2015-10-15 06:48:33

shouldn't the "already complete" branch use setTimeout(resolve, 0) (or setImmediate, if available) to ensure that it's called asynchronously?

@Jeff Bowman supports Monica 2016-08-14 21:17:41

@Alnitak Calling resolve synchronously is fine. The Promise's then handlers are guaranteed by the framework to be called asynchronously, regardless of whether resolve is called synchronously.

Related Questions

Sponsored Content

93 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 6260204 View
  • 7817 Score
  • 93 Answer
  • Tags:   javascript arrays

76 Answered Questions

[SOLVED] How can I convert a string to boolean in JavaScript?

  • 2008-11-05 00:13:08
  • Kevin
  • 1861992 View
  • 2389 Score
  • 76 Answer
  • Tags:   javascript

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

20 Answered Questions

[SOLVED] Checking if a key exists in a JavaScript object?

  • 2009-07-08 13:21:32
  • Adam Ernst
  • 1866175 View
  • 2818 Score
  • 20 Answer
  • Tags:   javascript object

56 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

41 Answered Questions

[SOLVED] Is there an "exists" function for jQuery?

  • 2008-08-27 19:49:41
  • Jake McGraw
  • 734238 View
  • 2701 Score
  • 41 Answer
  • Tags:   javascript jquery

4 Answered Questions

58 Answered Questions

[SOLVED] How do I redirect to another webpage?

10 Answered Questions

[SOLVED] How to access the correct `this` inside a callback?

Sponsored Content