Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js async/await using with MySQL

I need to get all results synchronized and append to a string with async/await keywords like c#.

I am new to node.js and I can not adapt this new syntax to my code.

var string1 = ''; var string2 = ''; var string3 = ''; var string4 = '';  DatabasePool.getConnection(function(err, connection) {          connection.query(query,function (err, result) {             if (err){};             string1 = result;         });          connection.query(query,function (err, result) {             if (err){};             string2 = result;         });               connection.query(query,function (err, result) {             if (err){};             string3 = result;            });          connection.query(query,function (err, result) {             if (err){};             string4 = result;         });          //I need to append all these strings to appended_text but          //all variables remain blank because below code runs first.        var appended_text = string1 + string2 + string3 + string4; }); 
like image 580
Burc Hasergin Avatar asked May 16 '17 14:05

Burc Hasergin


People also ask

How use async await in MySQL query?

Using async/await with MySQL But it works the same, so both the query() and close() functions return a promise. As you can see, the callback parameter is expected to be a function returning a promise. Here we use the async keyword with an arrow function to easily create an asynchronous callback function.

Is MySQL query async?

Any MySQL client that supports the X Protocol can provide asynchronous execution, either using callbacks, Promises, or by explicitly waiting on a specific result at the moment in time when it is actually needed.

CAN node js interact with MySQL?

Once you have MySQL up and running on your computer, you can access it by using Node. js. To access a MySQL database with Node. js, you need a MySQL driver.

Can we use async await in node js?

Async functions are available natively in Node and are denoted by the async keyword in their declaration. They always return a promise, even if you don't explicitly write them to do so. Also, the await keyword is only available inside async functions at the moment – it cannot be used in the global scope.


1 Answers

if you happen to be in Node 8+, you can leverage the native util.promisify() with the node mysql.

Do not forget to call it with bind() so the this will not mess up:

const mysql = require('mysql'); // or use import if you use TS const util = require('util'); const conn = mysql.createConnection({yourHOST/USER/PW/DB});  // node native promisify const query = util.promisify(conn.query).bind(conn);  (async () => {   try {     const rows = await query('select count(*) as count from file_managed');     console.log(rows);   } finally {     conn.end();   } })() 
like image 174
LeOn - Han Li Avatar answered Oct 05 '22 05:10

LeOn - Han Li