0

I am trying to push rows in dataArray but it returns a blank array in the response.

 let dataArray = [];
            for (let id=1; id <= 5; id++) {
                dbConnection.query("SELECT firm_name, id FROM stockist WHERE id=?", id, function (error, rows) {
                    if (error) throw error;
                    else {
                        dataArray.push(rows);
                    }
                });
                // console.log("data "+id+" :", data);
            }
4
  • What database are you using? Commented Jul 25, 2020 at 11:31
  • Does this answer your question? How to pass parameters to mysql query callback in nodejs Commented Jul 25, 2020 at 11:43
  • Danizavtz thanks for your response. I am using mysql database. Commented Jul 25, 2020 at 11:58
  • thanks Nikhil Bhandari. this is not my problem, I want to push rows into global variable dataArray. Commented Jul 25, 2020 at 12:05

1 Answer 1

1

You are using Async / Await which is an asynchronous operation hence it won't be possible for you to print the data outside of async. Hence you are going to have to store the async result in a variable and then simply check if data exist then print.

   let dataArray = [];

   for (let id=1; id <= 5; id++) {
        let result = null;
        result = await dbConnection.query("SELECT firm_name, id FROM stockist WHERE id=?", id);
        if (result) {
           console.log(result) //=====> it should contain all rows
           dataArray.push(result);
           // console.log("data "+id+" :", data);
        }
    }
Sign up to request clarification or add additional context in comments.

4 Comments

thanks Mr. Khan. But I want to push rows data into dataArray. is that possible?
Done. Check now. You don't need callback since you are using async/await just console.log it and you will find all rows in the result.
<ref *1> Query { _events: [Object: null prototype] { error: [Function (anonymous)], packet: [Function (anonymous)], timeout: [Function (anonymous)], end: [Fun
result print this type of object. how I retrieve rows from that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.