node.js + request => node.js + bluebird +请求
我试图了解如何用promise来编写代码。 检查我的代码PLZ。 这是对的?
Node.js +请求:
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.getAsync(url) .spread(function(response, body) {return body;}) .then(JSON.parse) .then(function(json){console.log(json)}) .catch(function(e){console.error(e)});
如何检查回复状态? 我应该使用,如果从第一个例子或更有趣的东西?
您可以简单地检查spread
处理程序中response.statusCode
是否不是200,并从中引发Error
,以便catch
处理程序将负责处理它。 你可以像这样实现它
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);
如果你注意到,我们从spread
处理程序返回parsing的JSON,因为JSON.parse
不是一个asynchronous函数,所以我们不必在单独的处理程序中完成。
检查状态码的一种方法是:
.spread(function(response, body) { if (response.statusCode !== 200) { throw new Error('Unexpected status code'); } return body; })