在NodeJs中使用mariadb查询来使用asynchronous的正确方法是什么?

我是新来asynchronous/等待。

我试图使用asynchronous和等待,但查询不等待,它发生在最后和页面呈现之前的查询,所以我不能得到正确的答案呈现页面上。

这是我的代码之前使用asynchronous等待

orderMiddleware.newOrder = function (req, res) { var total = 0 var curr_total = 0 // get items from cart c.query('select * from cart where user_id=:userId', { userId: req.user.ID }, function (err, cart) { if (err) { console.log(err) } else { cart.forEach(function (item) { // Find item from DB and check their price c.query('select * from products where id=:id', { id: item.item_id }, function (err, foundItem) { if (err) { console.log(err) } else { curr_total = foundItem[0].price * item.quantity console.log("currenttotal" + curr_total) total += curr_total console.log(total) } }) }) console.log(total) console.log(curr_total) // Calculate total price // Multiply all items with their quantity res.render('orders/new', { cart: cart, total: total }) } }) } 

但是这不能正常工作。 console.log(total)发生在查询之前,所以结果为零,并在呈现的页面中呈现零。 同样的事情发生,如果我使用asynchronous。 我用错了吗?

在使用asynchronous等待 –

 orderMiddleware.newOrder = async (req, res) => { var total = 0 var curr_total = 0 // get items from cart var A= c.query('select * from cart where user_id=:userId', { userId: req.user.ID }, async (err, cart) => { if (err) { console.log(err) } else { cart.forEach(async (item) => { // Find item from DB and check their price await c.query('select * from products where id=:id', { id: item.item_id }, async (err, foundItem) =>{ if (err) { console.log(err) } else { curr_total = foundItem[0].price * item.quantity console.log("currenttotal" + curr_total) total += curr_total console.log(total) } }) }) await console.log(total) // await console.log(curr_total) // Calculate total price // Multiply all items with their quantity await res.render('orders/new', { cart: cart, total: total }) } }) } 

我尝试不使用callback如:

 var A= c.query('select * from cart where user_id=:userId', { userId: req.user.ID }) 

但那么我怎么能得到查询的输出? console.log(A)显示不同的结果。

你不能因为这个函数没有返回promise。 你可以使用一个由30个部分组成的库(例如es6-promisify )来使这些函数成为可能,或者你可以自己把它们包装起来。

一旦函数返回一个Promise,你可以等待它。

例如,对于上述情况,解决scheme可能如下:

 const execQuery = (sql, params) => new Promise((resolve, reject) => { query(sql, params, (error, data) => { if (error) { reject(error); } else { resolve(data); } }); }); const logCartItem = async (userId) => { try { const items = await execQuery('select * from cart where user_id=:userId', { userId }); items.forEach(console.log); } catch (error) { console.error(error); } }; 

假设你正在使用node-mariasql包。 简短的回答是你不能使用async/await因为这个包不支持Promise 。