gpt4 book ai didi

javascript - Bluebird promise : catching errors

转载 作者:行者123 更新时间:2023-11-30 16:44:09 25 4
gpt4 key购买 nike

在 Bluebird 的 promise 库的帮助下,我在 Facebook 的 Graph API 上使用请求模块。通过传入错误的 key 来测试 catch 方法。

这里有两个问题:1、为什么我用promise的时候response是一个数组?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));
}
});

最佳答案

  1. Why is the response in an array when I use promise?

因为 request 库通过使用多个参数解析回调违反了回调契约。 Bluebird 没办法,只能用数组包裹起来。您可以轻松地使用 .get(0).get(1) 来访问特定属性。

request.getAsync("...").get(0); // just the response
request.getAsync("...").spread(function(response, body){ // spread arguments
// ...
});
  1. Why is the clientError predicate is not being called at all?

因为 promise 没有处于异常状态,所以之前的 promise resolvedthen 回调运行。

关于javascript - Bluebird promise : catching errors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31501550/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com