Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async function await not waiting

Tags:

node.js

mysql

I have an async function that I am using to query mysql database in Node.js. I am waiting for the result of the query execution and inserting the result into an array.

  async function getOpenOrders() {
    try {
        const arrayLoads = [],
            last4Orders = await pool.query( `${query1} ` )
        // console.log(last4Orders)
        for ( let i = 0; i < last4Orders.length; i++ ) {
            // console.log(last4Orders[i].orderID)
            console.log( arrayLoads )
            console.log( `===================` )
            const rows = await pool.query( `${query2}` )
            console.log( rows )
            arrayLoads.push( rows )
            // console.log(arrayLoads)
        }
        // console.log(rows[0])
        // console.log(arrayLoads)
        res.send( arrayLoads )
    } catch ( err ) {
        console.log( err )
    }
}

getOpenOrders()

However, the await query inside the for loop is not stopping the sync code because my console.log() displays something like:

    []
    ===================
    []
    [ [] ]
    ===================
    []
    [ [], [] ]
    ===================
    [RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 },
      RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 }]
[ [],
  [],
[RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 },
      RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 }]
===================
[RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 },
      RowDataPacket { Number: '4732', Test: 'TQLM-384', User: 23 }]
like image 551
jedu Avatar asked May 15 '26 05:05

jedu


1 Answers

mysql pool.query method returns a callback, if you want to use async await, try to promisify the method and then use async await

 const {promisify} = require('util');
    async function getOpenOrders() {
        try {
            const arrayLoads = [],
                query = promisify(pool.query).bind(pool);
                last4Orders = await query( `${query1} ` )
            // console.log(last4Orders)
            for ( let i = 0; i < last4Orders.length; i++ ) {
                // console.log(last4Orders[i].orderID)
                console.log( arrayLoads )
                console.log( `===================` )
                const rows = await query( `${query2}` )
                console.log( rows )
                arrayLoads.push( rows )
                // console.log(arrayLoads)
            }
            // console.log(rows[0])
            // console.log(arrayLoads)
            res.send( arrayLoads )
        } catch ( err ) {
            console.log( err )
        }
    }

    getOpenOrders()
like image 112
Nayan Patel Avatar answered May 17 '26 01:05

Nayan Patel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!