Unnesting Node database calls

后端 未结 5 877
半阙折子戏
半阙折子戏 2021-01-19 03:27

I have an ordinary

var express = require(\'express\')

Node express www page, using session, pug, etc as usual. My db calls

var         


        
5条回答
  •  暖寄归人
    2021-01-19 03:54

    Promise.all() method seems a more famous and cleaner way to make multiple calls in parallel like your use case.

    But there is one more alternate way. : Multiple statement queries

    To use this feature you have to enable it for your connection:

    var connection = mysql.createConnection({multipleStatements: true});
    

    Once enabled, you can execute multiple statement queries like any other query:

    db.query('SELECT cats; SELECT dogs', function (error, results, fields) {
      if (error) throw error;
      // `results` is an array with one element for every statement in the query:
      console.log(results[0]); // [{cat1,cat2}]
      console.log(results[1]); // [{dog1,dog2}]
    });
    

    It is technically more efficient as requires less back and forth with MySQL connection.

    (However, this feature is disabled by default as it allows for SQL injection attacks if values are not properly escaped). To use this feature you have to enable it for your connection.)

提交回复
热议问题