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?
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);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With