user2085143
user2085143

Reputation: 4232

Node Request Library - Promise Refactoring

I am using the Node request library which can be found at the following link

https://github.com/request/request

I have a number of functions which look like the following

function doRequest() {

    return new Promise(function(resolve,reject) {

        request('some-url', function(error,response,body) {

                if (!error && response.statusCode === 200) {
                    resolve(body)
                }
        });

    });

}

I then call these functions like so

doRequest()
    .then(function(response){
        console.log(response);
    })

My question is, is there a way of writing my doRequest function without having to create a new Promise? I feel like it is awkward looking and could possibly be an anti-pattern? Sort of how in AngularJS you often see people using

$q.defer() 

when making http calls, when the http call already returns a promise.

Any advice would be great.

Upvotes: 0

Views: 64

Answers (1)

Alnitak
Alnitak

Reputation: 339955

If you wanted to make Promises manually based on the results of the request() method then that is the right way to do it (although a reject() call on error is also required).

However that request library already appears to support the Bluebird Promise library's Promisify function, which can automatically wrap those functions into ones that return Promises.

Upvotes: 1

Related Questions