0

I'm unable to get the data from database while running query inside the loop in node.js

when I run console.log(data) inside query then it's showing the data like code blew

app.post("/wtrecord/get/getall",authcheck,(req,res)=>{
    let data = []
    let token = req.body.token
    con.query("SELECT date,SUM(hour_spend) FROM wtrecord WHERE user_token=? GROUP BY date",[token],(err,dates)=>{
        if(err) throw err
         if(dates){
             async.ForEach
            for(let i=0;i<dates.length;i++){
                console.log(dates[i].date)
                con.query("SELECT date,SUM(hour_spend) as totalhour,wtcategory.category_name FROM wtrecord INNER JOIN wtcategory ON wtrecord.category_uid=wtcategory.uid WHERE wtrecord.user_token=? AND wtrecord.date=? GROUP BY category_uid",[token,dates[i].date],(err,result)=>{
                    data[dates[i].date] = result
                    console.log(data)
                })
            }
            console.log("This is the real data")
            console.log(data)
        }else{

        }
    })
    res.send(data)
})

but whenever I run the console.log(data) outside the second query it's didn't show anything even data variable is not appending.

Thanks

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    In order for `data[dates[i].date] = result` to work, your `data` must be declared as `let data = {}`. If you want `data` to be an array, you need to use `push()` instead. – PsyGik Jul 04 '21 at 13:02
  • I agree with @PsyGik, I also recommend using async –  Jul 04 '21 at 13:03
  • 1
    Does this answer your question? [How to return the response from an asynchronous call](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – CherryDT Jul 04 '21 at 13:06
  • You are returning `data` before (temporally speaking, not in terms of position of the lines in source code) its contents are filled in. – CherryDT Jul 04 '21 at 13:07
  • Yes i have also tried with `let data = {}` but it also return `{}` empty braces – Mirza Hasnat Jul 04 '21 at 14:10
  • Thank you all I just solved this error by adding this code inside the second query: `if((i+1)===dates.length){ res.send(data) }` – Mirza Hasnat Jul 04 '21 at 17:11

0 Answers0