我是节点js中的新手,我在节点js中使用Promise中间件。 但我没有发现它的文档对我有用,也无法理解如何在一个请求中使用两个回调,或者如何使用多个回调。 请帮助我。
这是我的代码
//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!
});
寻找解决方案
在请求完成后,我必须在页面上发送数据。
2.如何使用render
或任何其他方式管理对象中的响应并将其发送到页面?
答案 0 :(得分:1)
我的第一个建议是找到一种以原生方式宣传client.get
的方法,我不确定它代表什么样的lib,并且它不遵循节点样式的回调为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.
});