我有一个异步函数,用于查询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 }]
答案 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()