node.js mysql-嵌套查询和异步/等待

mw3dktmi  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(411)

我在google或stackoverflow上找不到任何答案,也许你能帮我。我将node.js与mysql和express一起使用。
由于node.js是异步的,所以我使用async/await。
此应用程序应返回如下嵌套对象:

[{
      "name":"Name1",
      "additionalData": [
       {
        "data1": "data", 
        "data2": "data"
       }
      ]
    },
      {"name":"Name2",
      "additionalData": [
       {
        "data1": "data", 
        "data2": "data"
       }
      ]
    }]

这是代码(简化):

var express = require('express');
var mysql = require('mysql');
var app = express();

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "password",
    database: "database"
  });

con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

async function getData() { 
      var sql = 'Select name from users' 

      let promise = new Promise((resolve, reject) => {

        con.query(sql, async (err, resultSet) => { 
          if (err) reject(err); 

          let promisesub = new Promise((resolvesub, rejectsub) => {
            con.query('Select data from othertable', (err, rs) => { 
              resolvesub(rs)       
            }) 
          })

          resultSet.forEach(async (row) => { 
            row.additionalData = await promisesub;
            console.log(row)
           }); 

          resolve(resultSet);
        }) 

      })

      let result = await promise;

      return result;
} 

app.get('/', function (req, res) { 

  getData().then(function(rows) { 
    res.send(rows) 
  }).catch(function(err) { 
    console.log(err) 
  }) 
}); 

app.listen(3000, function () {
  console.log('Backend listening on port 3000!');
});

所以如果我打电话http://localhost:3000/i仅获取名称(不包含第二个查询的附加数据):

[{"name":"Name1"},
{"name":"Name2"}]

问题是只返回第一个承诺的结果。foreach循环中的代码应该为每一行分配额外的数据。代码正在工作(日志给出了正确的输出),但是在第一个承诺被发回后执行。
我如何才能让第一个承诺等待,直到额外的数据被分配给对象?
非常感谢你!
致以最诚挚的问候

r1wp621o

r1wp621o1#

Select data from othertable

从该表中获取所有数据,而不考虑关联的“名称”是什么。
此外,您正在做大量sql中“琐碎”的工作。这为您完成了内部循环的所有工作:

SELECT  n.name, a.data1, a.data2
    FROM  Names AS n
    JOIN  AdditionalData AS a  ON a.name = n.name

(警告:没有看到 SHOW CREATE TABLE ,我不能肯定我猜到了数据的模式。)
一般来说,如果您想“嵌套查询”,那么您的sql操作是“错误的”。

slmsl1lt

slmsl1lt2#

使用下面的代码获取类别和子类别。如何按类别获取子类别?

async function getData() {
var sql1 = 'Select name from category'
let promise = new Promise((resolve, reject) => {

    sql.query(sql1, async (err, resultSet) => {
        if (err) reject(err);

        // asyncForEach
        async function asyncForEach(array, callback) {
            for (let index = 0; index < array.length; index++) {
                await callback(array[index], index, array)
            }
        }

        //Subdata

        const start = async () => {
            await asyncForEach(resultSet, async (row) => {
            let promisesub = new Promise((resolvesub, rejectsub) => {
              sql.query(`Select * from subcategory cat_id=${row.id}`, (err, rs) => {
                  resolvesub(rs)
              })
            })
                row.subcategory = await promisesub;
            })
            resolve(resultSet)
            //console.log('ready')
        };

        start()
    })
})

let result = await promise;
return result;
}
sauutmhj

sauutmhj3#

好吧,我读了这篇文章后找到了解决办法:
链接
文章说foreach函数不会等待回调完成,所以我实现了一个自己的asyncforeach函数。
以下是有效的代码:

var express = require('express');
var mysql = require('mysql');
var app = express();

var con = mysql.createConnection({
    host: "localhost",
    user: "root",
    password: "admin",
    database: "db"
  });

  con.connect(function(err) {
    if (err) throw err;
    console.log("Connected!");
  });

async function getData() { 
      var sql = 'Select name from user' 

      let promise = new Promise((resolve, reject) => {

        con.query(sql, async (err, resultSet) => { 
          if (err) reject(err); 

          // asyncForEach
            async function asyncForEach(array, callback) {
              for (let index = 0; index < array.length; index++) {
                await callback(array[index], index, array)
              }
            } 

            //Subdata
            let promisesub = new Promise((resolvesub, rejectsub) => {
              con.query('Select data from othertable', (err, rs) => { 
                  resolvesub(rs)       
          }) 
        })

          const start = async () => {
              await asyncForEach(resultSet, async (row) => {
                row.additionalData = await promisesub;
              })
          resolve(resultSet)
          //console.log('ready')
          };

          start()
        }) 
      })

      let result = await promise;

      return result;
} 

app.get('/', function (req, res) {

    getData().then(function(rows) { 
        //console.log('step 3 ',  rows); 
        res.send(JSON.stringify(rows))
      }).catch(function(err) { 
        console.log(err) 
      });
});

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
  });
vuktfyat

vuktfyat4#

下面我对您的代码做了一些修改,我们可以看到行为的发生(请看下面的内容)http://jsfiddle.net and 把这个代码扔到下面去看看,或者其他的游戏场地)

var con = {
        connect : function (fnc) { fnc()},
        query : function (sql, pr) {
            if (sql === 'Select name from users') {
              setTimeout(
                  () => pr(null,[{id:1},{id:2}]), 2000
              )
            } else {
              setTimeout(
                  () => pr(null,[{id:3},{id:4}]), 2000
              )
            }
        }
      }

      con.connect(function(err) {
          if (err) throw err;
          console.log("Connected!");
        });

      async function getData() { 
            var sql = 'Select name from users' 

            let promise = new Promise((resolve, reject) => {

              con.query(sql, async (err, resultSet) => { 
                if (err) reject(err); 

                let promisesub = new Promise((resolvesub, rejectsub) => {
                  con.query('Select data from othertable', (err, rs) => { 
                    resolvesub(rs)       
                  }) 
                })

                resultSet.forEach(async (row) => {
                  console.log('for each');
                  row.additionalData = await promisesub;
                  console.log(' step 1', row);
                 }); 

                resolve(resultSet);
              }) 

            })

            let result = await promise;

            return result;
      } 

      getData().then(function(rows) { 
          console.log('step 2 ',  rows); 
        }).catch(function(err) { 
          console.log(err) 
        });

归还的顺序正是这样

Connected!
(index):61 for each
(index):77 step 2  (2) [{…}, {…}]
(index):63  step 1 {id: 1, additionalData: Array(2)}
(index):63  step 1 {id: 2, additionalData: Array(2)}

我注意到的第一件事是,问题不在您使用的libs中。它位于您创建的第二个异步环境中,该环境保存进程,但仅在foreach函数内部。因此,它将通过foreach,即使foreach的顺序是正确的。。。对于这种情况,请使用其他辅助承诺:

let auxProm = new Promise(resolve => {
            resultSet.forEach(async (row) => {
              console.log('for each');
            row.additionalData = await promisesub;
              console.log(' step 1', row);
            }); 
          resolve(resultSet)
        })
        auxProm.then(auxResultSet => resolve(auxResultSet));

相关问题