javascript - Writing to an array in a higher scope, from within a query's anonymous function -


i need return value function, gets information query. i'm having trouble passing information query's anonymous function container function.

i tried creating array in higher scope (the container function) , having query function write array per result, didn't seem work. tried passing array query's anonymous function. did not appear work either.


here's function (executed within node):

function retrievesales(connection,timeframe) {      var sales = new array();      connection.query('select * sales_entries date between ? , ?',     timeframe,      function (err, rows, fields, sales) {          if (err) return callback(new error('failed connect'), null);          connection.end();          (x = 0; x < rows.length; x++) {             sales.push(rows[x]);         }      });      console.log('sales returned: ' + json.stringify(sales, null, 4));      return sales;  } 

which result in 'cannot call method 'push' of undefined.

how should write sales array can return retrievesales()?

you dealing javascript's beautiful asynchronous-ness-icity. are trying return out of asynchronous method. try brush on how asynchronous programming works, , it'll make life much, easier; isn't hard, different. check out code sample, can , going.

// use callback handle results connection.query() function sales_cb(rows) {   var sales = [];   (x = 0; x < rows.length; x++) {     sales.push(rows[x]);   }   console.log('sales returned: ' + json.stringify(sales, null, 4)); }  function retrievesales(connection, timeframe) {   // connection.query() asynchronous - interact accordingly   connection.query('select * sales_entries date between ? , ?', timeframe,     function (err, rows, fields, sales) {       if (err) {         callback(new error('failed connect'), null);       } else {         // invoke sales_cb(sales) once loop done         sales_cb(rows);       }     }); } 

let me know if helps :)


Comments

Popular posts from this blog

user interface - How to replace the Python logo in a Tkinter-based Python GUI app? -

objective c - Greedy NSProgressIndicator Allocation -

how to set an OCR language in Google Drive -