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; });
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.
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.
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.
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.
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(); } })()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With