Bluebird promisifaction is a little magic, and request
is quite a mess (it's a function which behaves as an object with methods).
The specific scenario is quite simple: I have a request instance with cookies enabled, via a cookie jar (not using request
's global cookie handler). How can I effectively promisify it, and all of the methods it supports?
Ideally, I'd like to be able to:
request(url)
-> Promiserequest.getAsync(url)
-> Promiserequest.postAsync(url, {})
-> PromiseIt seems as though Promise.promisifyAll(request)
is ineffective (as I'm getting "postAsync is not defined").
The util. promisify() method defines in utilities module of Node. js standard library. It is basically used to convert a method that returns responses using a callback function to return responses in a promise object.
Promisify is used when you want to convert a callback function into a promise based function. Nowadays, is used promises because let the developers to write more structured code.
The following should work:
var request = Promise.promisify(require("request")); Promise.promisifyAll(request);
Note that this means that request
is not a free function since promisification works with prototype methods since the this
isn't known in advance. It will only work in newer versions of bluebird. Repeat it when you need to when forking the request object for cookies.
If you're using Bluebird v3, you'll want to use the multiArgs
option:
var request = Promise.promisify(require("request"), {multiArgs: true}); Promise.promisifyAll(request, {multiArgs: true})
This is because the callback for request is (err, response, body)
: the default behavior of Bluebird v3 is to only take the first success value argument (i.e. response
) and to ignore the others (i.e. body
).
you can use the request-promise module.
The world-famous HTTP client "Request" now Promises/A+ compliant. Powered by Bluebird.
Install the module and you can use request in promise style.
npm install request-promise
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