Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you properly promisify request?

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:

  • call request(url) -> Promise
  • call request.getAsync(url) -> Promise
  • call request.postAsync(url, {}) -> Promise

It seems as though Promise.promisifyAll(request) is ineffective (as I'm getting "postAsync is not defined").

like image 423
Madara's Ghost Avatar asked Feb 03 '15 20:02

Madara's Ghost


People also ask

What is the use of Promisify?

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.

What does Promisify mean?

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.


2 Answers

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).

like image 87
Benjamin Gruenbaum Avatar answered Oct 07 '22 16:10

Benjamin Gruenbaum


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 
like image 45
Arvind Sridharan Avatar answered Oct 07 '22 15:10

Arvind Sridharan