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?
source share