2015-07-19 159 views
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)); 
     } 
    }); 

回答

2
  1. 爲什麼在一個陣列的響應,當我使用的承諾?

因爲request庫違反通過解決與多參數回調回調合同。藍鳥別無選擇,只能將其包裝在一個數組中。您可以輕鬆地使用.get(0).get(1)以訪問特定屬性。

request.getAsync("...").get(0); // just the response 
request.getAsync("...").spread(function(response, body){ // spread arguments 
     // ... 
}); 
  • 爲什麼clientError謂詞不被稱爲在所有?
  • 由於前景不處於異常狀態,先前的承諾解決then回調跑去。