1
我在Bluebird的承諾庫的幫助下,在Facebook的Graph API上使用了請求模塊。通過傳遞錯誤的密鑰來測試catch方法。藍鳥承諾:捕獲錯誤
這裏有兩個問題: 1.爲什麼當我使用promise時數組中的響應? 2.爲什麼clientError謂詞沒有被調用?
var request = Promise.promisifyAll(require('request'));
var queryObj = {
client_id: config.client_id,
redirect_uri: config.redirect_uri,
client_secret: config.wrong_client_secret,
code: req.query.code
};
var reqObj = {
url: 'https://graph.facebook.com/v2.3/oauth/access_token',
qs: queryObj
};
request.getAsync(reqObj)
.then(function (contents) {
console.log('success ' + JSON.stringify(contents));
/*
Produces (simplified it for brevity)
[{"statusCode":400,"body":"{\"error\":{\"message\":\"Error validating client secret.\"}}"}]
*/
}).catch(clientError, function(e) {
console.log('error: ' + e);
});
function clientError(contents) { // this is not called at all
var statusCode = contents[0].statusCode;
console.log('checking for error...' + statusCode);
return statusCode >= 400 && statusCode < 500;
}
// without promise:
var request = require('request');
request(reqObj, function (error, response, body) {
if (!error && response.statusCode == 200) {
console.log(JSON.stringify(response));
/* Response: (simplified it for brevity)
{"statusCode":400,"body":"{\"error\":{\"message\":\"Error validating client secret.\"}}"}
*/
} else {
console.log(JSON.stringify(response));
}
});