Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Promises and irregular callbacks

I'm playing around with a promises control flow, using bluebird. Bluebird provides a .promisify() method for converting a regular callback function into a promise function, but I'm unclear what I should be doing when the function is irregular. For example the method signature for a requestjs request is

request(url, callback)

where callback is

err, res, body

instead of the regular

err, res

How should I be converting this to a promise?

like image 394
Dan Avatar asked Oct 13 '13 09:10

Dan


1 Answers

Promise.promisify() can work with such callbacks as well. When multiple values are given, they'll just be passed along in an Array:

var Promise = require('bluebird');
var request = Promise.promisify(require('request'));

request('http://stackoverflow.com').then(function (result) {
    var response = result[0];
    var body = result[1];

    console.log(response.statusCode);
});

Which can also be .spread() back to individual arguments as Esailija mentioned in the comments:

// ...

request('http://stackoverflow.com').spread(function (response, body) {
    console.log(response.statusCode);
});
like image 62
Jonathan Lonowski Avatar answered Nov 15 '22 13:11

Jonathan Lonowski