javascript - Promise middleware in node js callback functions how to use multiple then? -
am newby in node js, using promise middleware in node js. didn't find documentation useful me , unable understand how use 2 callbacks in 1 request or how should use multiple then. please me thanks.
here code
//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 app type req"); if(data.status == "success"){ return resolve(data); } else{ reject ("unamble 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 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 app req"); if(data.status == "success"){ return resolve(data); } else{ reject ("unamble 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! });
solutions looking for 1. have send data on page after both request complete. 2. how can manage response in object , send page using render
or alternative?
my first advice find way promisify client.get
in native fashion, not sure lib represent, , not following node-style callback fun(err, data)
, aside, assuming, have single request server, carry multiple requests else, bundle responses , respond requester right?
i restructure code like
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 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)); // send response once both of promises finish promise.all([p1, p2]).then(function(){ res.render('app', resultjson); }); // not adding error handler since both previous ones should not throw any. });
Comments
Post a Comment