gpt4 book ai didi

javascript - 使用 Bluebird 链接多个请求

转载 作者:行者123 更新时间:2023-11-30 00:12:18 25 4
gpt4 key购买 nike

我正在尝试使用 BlueBird 转换我现有的代码,请建议一个链接多个请求的最佳选项。每个回调中发生的错误需要重定向到以不同的错误呈现。

request(option1, function (error, response, body) {
if (!error && response.statusCode == 200) {
var data= JSON.parse(body);

if(data.valid){

if(data.expired){

next();
} else {

request(option2, function (error2, response2, body2) {
var data2= JSON.parse(body2);
if(data2.valid) {
request(option3, function (error3, response3, body3) {
next();
})
} else {
res.json({error:'Error1'});
}
})

}
} else {
res.json({error:'Error2'});
}
} else {
res.json({error:'Error3'});
}
})

最佳答案

这非常简单,还要注意您当前的代码不处理第二个和第三个请求中的错误,而这样做:

var request = require("request-promise"); // request - converted to bluebird

request(option1).then(data=> {
if(!data.valid) throw Error("Error3");
if(data.expired) return;
return request(option2).then(JSON.parse);
}).then(data2 => {
if(!data2) return; // didn't need to fetch additional data
if(!data2.valid) throw Error("Error2");
return request(option3);
}).then(() => {
next();
}, e => {
res.json(error: e.message);
// better log this.
});

关于javascript - 使用 Bluebird 链接多个请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35968750/

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