我将尝试解释如何使用 Promise 编写代码。
请检查我的代码是否正确。
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)});
如何检查响应状态?我应该使用第一个示例中的if语句还是其他更有趣的方法?
jsonString
是从哪里来的? - thefourtheye