node.js - Extract data from variables inside multiple callbacks in javascript -
i'm ok javascript , callbacks, i'm getting annoyed @ , need call on the world of stackoverflow help.
i have written function, used in following way:
var meth = lib.function(a,b); // meth should hold array of properties { c, d } once executed
so inside lib.js, have structure like:
exports.function = function (a,b) { database.connect(params, function(err,get){ get.query(querylang, function(err, results){ var varsiwanttoreturn = { var1: results[i].foo, var2: results[i].bar }; }); }); // how return 'varsiwanttoreturn'? };
i have seen things incorporating callback() function, i'm not sure how works. i've seen people use exec() - again, im not sure on how or why use it.
please :) in advance.
well, it's asynchronous if attempt return - it'll return undefined. in javascript (sans new yield
keyword) functions execute top bottom synchronously. when make io call database call - still executes synchronously. in fact- when variwanttoreturn
gets population function has long run , terminated.
what left same thing async functions database.connect
, get.query
, have function take callback:
exports.function = function (a,b, callback) { database.connect(params, function(err,get){ if(err) return callback(err, null); // don't suppress errors get.query(querylang, function(err, results){ if(err) return callback(err, null); // don't suppress errors var varsiwanttoreturn = { var1: results[i].foo, var2: results[i].bar }; callback(null, varsiwanttoreturn); }); }); };
then you'd call like
myexportedfunction(mya,myb, function(err, resp){ if(err) recoverfromerror(err); // varsiwanttoreturn contained in `resp` });
Comments
Post a Comment