How do you properly promisify request?

Madara's Ghost picture Madara's Ghost · Feb 3, 2015 · Viewed 35.1k times · Source

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

Answer

Benjamin Gruenbaum picture Benjamin Gruenbaum · Feb 3, 2015

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