Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Node.js 在NodeJs中使用asyncwait和mariadb查询的正确方法是什么?_Node.js_Express_Asynchronous_Mariadb_Mariasql - Fatal编程技术网

Node.js 在NodeJs中使用asyncwait和mariadb查询的正确方法是什么?

Node.js 在NodeJs中使用asyncwait和mariadb查询的正确方法是什么?,node.js,express,asynchronous,mariadb,mariasql,Node.js,Express,Asynchronous,Mariadb,Mariasql,我不熟悉异步/等待 我尝试使用async和await,但查询没有等待,它最终发生了,页面在查询之前呈现,因此我无法在呈现的页面上获得正确的答案 这是我在使用async await之前的代码 orderMiddleware.newOrder = function (req, res) { var total = 0 var curr_total = 0 // get items from cart c.query('select * from cart where

我不熟悉异步/等待

我尝试使用async和await,但查询没有等待,它最终发生了,页面在查询之前呈现,因此我无法在呈现的页面上获得正确的答案

这是我在使用async await之前的代码

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 })
            }
        })
}
然而,这并不能正常工作。log(total)发生在查询之前,因此结果为零,并在呈现页面中呈现零。 如果我使用async,也会发生同样的事情。我用错了吗

使用异步等待后-

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 })
            }
        })
}
我尝试不使用回调,如:

var A=  c.query('select * from cart where user_id=:userId',
        { userId: req.user.ID })
但是,我怎样才能得到查询的输出呢?
log(A)显示不同的结果。

假设您使用的是
节点mariasql
包。简单的回答是,您不能使用
async/await
,因为程序包不存在。

您不能使用,因为函数不返回承诺。例如,您可以使用由三十部分组成的库来实现这些函数,也可以自己包装这些函数

函数返回承诺后,您可以等待它

例如,对于上述情况,解决方案可以是:

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);
  }
};

有了节点mariasql,promisify就很容易使用了

const util = require('util')

const asyncQuery = util.promisify(c.query);

const rows = await asyncQuery.call(c, 'SELECT product FROM products WHERE id = :id', { id }, { useArray: false, metaData: false })

哦,谢谢。有没有别的办法做这种事?因为这个原因,我无法得到总金额。