node.js - Q.js variables passing in parallel flows -


while implementing promises got code:

var mongoclient = require('mongodb').mongoclient mongoclient.connect(db_uri, function(err, db) {     if(err) throw err;     var ccoll = db.collection('cdata');     app.locals.dbstore = db; } var json= {} //auth wrapped mongo collection var auth = app.locals.auth; var coll = app.locals.dbstore.collection('data'); var ucoll = app.locals.dbstore.collection('udata'); var ccoll = app.locals.dbstore.collection('cdata'); var q = require('q'); //testing _id  in database var _id = require('mongodb').objectid('530ede30ae797394160a6856'); //auth.getuserbyid = collection.findone() var getuser = q.nbind(auth.getuserbyid, auth); //getuserinfo gives detailed information each user var getuserinfo = q.nbind(ucoll.findone, ucoll); var getuserdata = q.nbind(ccoll.findone, ccoll); //"upr" group of users //getusers gives me list of users, belonging group var getusers = q.nbind(ucoll.find, ucoll); //auth.getuserbyid = collection.find() var listusers = q.nbind(auth.listusers, auth); var uupr = {} var cupr = {} getuserinfo({_id:_id})      .then(function(entry){         console.log('entry:', entry);         uupr = entry;         var queue = [getusers({upr:entry.name}), getuserdata({_id:entry._id})]         return q.all(queue);     } )     .then(function(array2){         console.log('array2:', array2);         cupr = array2[1]         var cursor = array2[0]         var cfill =  q.nbind(cursor.toarray, cursor);         return cfill();     } )     .then(function(data){         json = {data:data, uupr:uupr, cupr:cupr}         console.log('json:', json)         res.render('test', {json : json.stringify(json)})     } ) 

its work can described diagram:

getuserinfo()==>(entry)--+-->getusers()=====>array2[0]--+-->populate user list===>data--->render                          |                              |                          +-->getuserdata()==>array2[1]--+ 

i've used external variables uupr , cupr store data first .then calls.

so have 2 problems:

1) avoid using external variables.

2) rearrange code alternative flow diagram.

 getuserinfo()==>(entry)--+-->getusers()==>userslist-->populate user list==>usersdata-+->render                           |                                                           |                           +-->getuserdata()====>uprdata-------------------------------+ 

any advice appreciated

try along lines of pseudo-code:

getuserinfo().then(function(userinfo) {     return q.all([         userinfo,         getusers(... userinfo ...).then(convert array),         getuserdata(... userinfo ...)     ]) }).spread(function(userinfo, usersarray, userdata) {     res.render(...) }, function(err) {     handle error }).done() 

Comments

Popular posts from this blog

c# - How to get the current UAC mode -

postgresql - Lazarus + Postgres: incomplete startup packet -

javascript - Ajax jqXHR.status==0 fix error -