gpt4 book ai didi

javascript - Node js中的Promise中间件回调函数如何使用多个呢?

转载 作者:太空宇宙 更新时间:2023-11-04 00:51:17 24 4
gpt4 key购买 nike

我是 Node js 的新手,正在使用 Promise Node.js 中的中间件。但我没有发现它的文档对我有用,并且无法理解如何在一个请求中使用两个回调或应该如何使用多个回调。请帮助我谢谢。

这是我的代码

//get application types
var p1 = new Promise(function(resolve, reject) {
console.log("in p1");
var url = tURL+'applicationType/getAll'
var args = {
headers:{"AuthKey": req.session.name}
};
client.get(url, args, function(data,response) {
console.log(data, "in get all app type req");
if(data.status == "success"){
return resolve(data);
}
else{
reject ("unamble to get data!")
}
});
});

p1.then(function(data) {
console.log(data.response.applicationType, "in p1 then", data)
//load page after data
res.render('app', {
message: req.session.name,
uName: "THE MECHANIC",
applist: data.response.applicationType
});
},function(reason) {
console.log(reason, "reason in not then"); // Error!
});



//get all application
var p2 = new Promise(function(resolve, reject){
console.log("in p2");
var url = tURL+'applications'
var args = {
headers:{"AuthKey": req.session.name}
};
client.get(url, args, function(data,response) {
console.log(data, "in get app req");
if(data.status == "success"){
return resolve(data);
}
else{
reject ("unamble to get data!")
}
});
});

p2.then(function(data) {
console.log(data.response, "in p2 then", data)
//load page after data
res.render('app', {
appList: data.response
});

},function(reason) {
console.log(reason, "reason in not p2"); // Error!
});

正在寻找的解决方案1.两个请求完成后,我必须在页面上发送数据。2. 如何管理对象中的响应并使用 render 或任何替代方法将其发送到页面?

最佳答案

我的第一个建议是找到一种以 native 方式 promisify client.get 的方法,我不确定它代表什么库,并且它不遵循 Node 样式回调 fun(err, data),除此之外,我假设您对服务器有一个请求,您向其他东西发送多个请求,然后捆绑所有响应并响应请求者,对吗?

我会重构代码,例如

function pGet(url, args){
return new Promise(function(resolve, reject){
client.get(url, args, function(data, response){
if(data.status === 'success') resolve(data);
else reject('unable to get data');
});
});
}

router.get('/api/someAPI', function(req, res, next){
var resultJSON = {
message: req.session.name,
uName: "THE MECHANIC"
}, args = { headers:{"AuthKey": req.session.name} },
p1, p2;

p1 = pGet(tURL+'applicationType/getAll', args)
.then(function(data){
resultJSON.applist = data.response.applicationType;
}).catch(console.log.bind(console));

p2 = pGet(tURL+'applications', args)
.then(function(data){
resultJSON.appList = data.response;
}).catch(console.log.bind(console));

// now we send the response once both of the promises finish
Promise.all([p1, p2]).then(function(){
res.render('app', resultJSON);
}); // not adding any error handler since both the previous ones should not throw any.

});

关于javascript - Node js中的Promise中间件回调函数如何使用多个呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32304790/

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