4

node.js async / waits to use with MySQL

 2 years ago
source link: https://www.codesd.com/item/node-js-async-waits-to-use-with-mysql.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

node.js async / waits to use with MySQL

advertisements

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){};
            string2 = result;
        });

        connection.query(query,function (err, result) {
            if (err){};
            string2 = 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;

});


Assuming that your ORM that you are using it promise-based you can do something like this

async function buildString() {
  try {
    const connection = await DatabasePool.getConnection();
    const string1 = await connection.query(query);
    const string2 = await connection.query(query);
    const string3 = await connection.query(query);
    const string4 = await connection.query(query);

    return string1 + string2 + string3 + string4;
  } catch (err) {
    // do something
  }
}

Any promise can be used with async/await by putting await in front of the call. However, notice that this function must be used within an async function "wrapper". You need to handle the errors in try/catch blocks.

I also want to point out that these 4 queries are not run simulatneously. You'll still need to use Promise.all for that.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK