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?
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?
Share edited Nov 1, 2013 at 16:13 Florian Margaine 60.8k15 gold badges93 silver badges120 bronze badges asked Oct 13, 2013 at 9:26 DanDan 3,2682 gold badges22 silver badges37 bronze badges1 Answer
Reset to default 14Promise.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.').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 ments:
// ...
request('http://stackoverflow.').spread(function (response, body) {
console.log(response.statusCode);
});