what is the correct way to use async await with mariadb query in NodeJs?

nodejs mysql async/await example
node.js mysql asynchronous query
node.js asynchronous database query
promise-mysql async await
nodejs mysql transaction async/await
nodejs mysql-promise example
nodejs tedious async/await
mysql2/promise

I'm new to async/await.

I'm trying to use async and await but the query is not waiting and it happens at last and the page renders before the query so I can't get the correct answer on rendered page.

Here is my code before using 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 })
            }
        })
}

However this doesn't work properly. console.log(total) happens before the query so the result is zero and it renders zero in the rendered page. Same thing happens if I use async. Am I using it wrong?

After using async await-

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

I tried without using callbacks like:

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

but then how can I get the output of the query? console.log(A) shows different results.

You can't because the functions don't return promises. You can promisify those function using a thirty-part library (for example es6-promisify) or you can wrap those by yourself.

Once a function returns a Promise, you can await it.

For example, for the above, a solution could be the following:

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.js, MySQL and async/await, The async/await way. Here's the same code implemented using the await keyword: const users = await db.query( 'SELECT * FROM users  I'm new to async/await. I'm trying to use async and await but the query is not waiting and it happens at last and the page renders before the query so I can't get the correct answer on rendered page.

Assuming you're using the node-mariasql package. Short answer is you can't use async/await because the package does not support Promises.

How to Interact With a Database Using Async Functions in Node.js , How to Interact With a Database Using Async Functions in Node.js I like to think of async functions as two parts: async and await. to get a connection to the database, use it to execute a query, and then close a connection. async function foo () {. return 42; } foo ().then ( result => console.log ( result ) ); This code will print 42. On the other hand, within an async function, you can use the await keyword with any promise, not only to call other async functions: const foo = Promise.resolve ( 42 ); console.log ( await foo );

With node-mariasql it's easy to use 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 })

Create a MySQL Database Middleware with Node.js and Async/Await, Write a robust MySQL database middleware for your next Node.js project This is how a database.js middleware could look like: What we're doing here is to promisify the pool.query function so that we can use async/await with it. Follow all the topics you care about, and we'll deliver the best stories for  Simple .then chains can be upgraded in a pretty straightforward way, so you can move to using async/await right away. function asyncTask () { return functionA() .then((valueA) => functionB(valueA)) .then((valueB) => functionC(valueB)) .then((valueC) => functionD(valueC)) .catch((err) => logger.error(err)) }

return value from mariadb in function nodejs - node.js - html, what is the correct way to use async await with mariadb query in NodeJs? - node.​js. To use Async/await, you need to use the async keyword when you define a request handler. (Note: These request handlers are known as called “controllers”. I prefer calling them request handlers because request handlers are more explicit). app.post('/testing', async (req, res) => { // Do something here }) Once you have the async keyword, you can await something immediately in your code.

Getting Started With the Node.js Connector, Mainly because every function in which I use the asynchronous function must also use then, eg make small test: let test = async function() { let x = await 11 return 1; } get errors By the way: get interested in query builder, for example knex.js. If I understand your code correctly, getSkus() is an async function that returns a  The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value.

MySQL examples in Node.js, Available through the Node.js repositories; install using npm. connectionLimit: 5 }); async function asyncFunction() { let conn; try { conn = await pool. is Promise. The callback API is provided for compatibility with the mysql and mysql2 APIs. Note: While you can certainly use a variety of other SQL clients, for the sake of keeping things simple and uniform, I've only included samples using the official MariaDB client. Connect to your MariaDB instance by executing the following command in a terminal window.

Comments
  • oh thanks. Is there any other way to do this kind of thing? I can't get total amount because of this.