nesting asynchronous queries in node.js -
i'm trying code function 2 queries , wish have access both record sets in final code-block; code looks similar to:
295 connection.query(sql1, function selectdb(err, results, fields) { 296 if (err) { 297 throw err; 298 } 299 300 result = results[0]; 301 console.log(result); 302 303 console.log(sql2); 304 connection.query(sql2, function selectdb(err, results, fields) { 305 if (err) { 306 throw err; 307 } 309 console.log(result);
problem var result retains first record set until after second query @304 , displays 'undefined' @309 (had record set in previous displays).
i don't know how pass first record set value inner code async code block @304; tried add result parameter;
304 connection.query(sql2, function selectdb(err, results, fields, result) {
result still undefined @309
help appreciated.
- callback argument names choice. there spec tells passed argument , slots may named aid further description, actual name of actual argument passed you. keeping expected name idea others reading code in future, can varied expedient. means can use results1 , results2 instead of results, in callbacks, if help.
- your second callback closure , can read variables in block defined.
- i've heard bad practice name anonymous function callbacks.
??? // variables sql1, sql2 need defined prior code below 295 connection.query(sql1, function(err, results1, fields1) { 295.1 var result; // dont make result global 296 if (err) { 297 throw err; 298 } 299 300 result = results1[0]; 301 console.log(result); 302 303 console.log(sql2); 304 connection.query(sql2, function(err, results2, fields2) { 305 if (err) { 306 throw err; 307 } 309 console.log(result); 310 console.log(results1); 311 console.log(results2); 312 }); 313 });
Comments
Post a Comment