Node.js + request => node.js + bluebird + request

I am trying to figure out how to write code using promises. Check out my plz code. It is right?

Node.js + request:

request(url, function (error, response, body) { if (!error && response.statusCode == 200) { var jsonpData = body; var json; try { json = JSON.parse(jsonpData); } catch (e) { var startPos = jsonpData.indexOf('({'); var endPos = jsonpData.indexOf('})'); var jsonString = jsonpData.substring(startPos+1, endPos+1); json = JSON.parse(jsonString); } callback(null, json); } else { callback(error); } }); 

Node.js + bluebird + request:

 request.getAsync(url) .spread(function(response, body) {return body;}) .then(JSON.parse) .then(function(json){console.log(json)}) .catch(function(e){console.error(e)}); 

How to check response status? Should I use if from the first example or something more interesting?

+5
source share
2 answers

You can simply check if response.statusCode not 200 in the spread handler and throw Error from this, so the catch handler will take care of this. You can implement it like this:

 var request = require('bluebird').promisifyAll(require('request'), {multiArgs: true}); request.getAsync(url).spread(function (response, body) { if (response.statusCode != 200) throw new Error('Unsuccessful attempt. Code: ' + response.statusCode); return JSON.parse(body); }).then(console.log).catch(console.error); 

And if you notice, we will return the processed JSON from the spread handler, because JSON.parse not an asynchronous function, so we do not need to do this in a separate then handler.

+11
source

One way to check the status code:

 .spread(function(response, body) { if (response.statusCode !== 200) { throw new Error('Unexpected status code'); } return body; }) 
0
source

All Articles