Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
162
rated 0 times [  167] [ 5]  / answers: 1 / hits: 38980  / 10 Years ago, tue, february 3, 2015, 12:00:00

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


More From » promise

 Answers
102

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


[#67963] Monday, February 2, 2015, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
daja

Total Points: 407
Total Questions: 103
Total Answers: 103

Location: Ghana
Member since Sun, Mar 27, 2022
2 Years ago
daja questions
Tue, Dec 21, 21, 00:00, 2 Years ago
Thu, Apr 23, 20, 00:00, 4 Years ago
Fri, Sep 6, 19, 00:00, 5 Years ago
Tue, Jul 23, 19, 00:00, 5 Years ago
;