异步功能等待不等待

时间:2019-09-06 05:35:37

标签: mysql node.js

我有一个异步函数,用于查询Node.js中的mysql数据库。我正在等待查询执行的结果并将结果插入到数组中。

  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()

但是,因为我的console.log()显示如下内容,所以for循环内的await查询并未停止同步代码:

    []
    ===================
    []
    [ [] ]
    ===================
    []
    [ [], [] ]
    ===================
    [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 }]

1 个答案:

答案 0 :(得分:3)

mysql pool.query方法返回一个回调,如果要使用async await,请尝试使该方法合理化,然后使用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()