我试图了解如何使用promise来编写代码。 查看我的代码plz。这是对的?node.js + request => node.js + bluebird +请求
的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 +蓝鸟+要求:
request.getAsync(url)
.spread(function(response, body) {return body;})
.then(JSON.parse)
.then(function(json){console.log(json)})
.catch(function(e){console.error(e)});
如何检查响应状态?我应该使用从第一个例子或更有趣的东西?检查状态代码
'jsonString'从哪里来的? – thefourtheye
@thefourtheye sry,忘记部分catch(e){...} –