我試圖瞭解如何使用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){...} –