【问题标题】:Nested queries in npm mysql node jsnpm mysql node js中的嵌套查询
【发布时间】:2020-08-21 12:03:24
【问题描述】:

调用嵌套查询。我需要在节点 js 的一个 api 调用中调用 2 个查询。我正在使用 npm mysql 库。第一个查询运行,但第二个不运行。如何一个一个地运行两个查询?

router.delete("/:id", async (req, res) => {
  conn.query(
    "Delete FROM assignedcourses WHERE CourseID = ?",
    req.params.id,
    async (err, results) => {
      if (err) throw err;
      conn.query(
        "Delete FROM courses WHERE CourseID = ?",
        req.params.id,
        async (err, results) => {
          res.send(results);
        }
      );
    }
  );
});

【问题讨论】:

  • 会发生什么?你的代码执行结果是什么?错误?!

标签: mysql node.js npm


【解决方案1】:

您可以使用 Promise “并行”运行命令。 https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/all

router.delete("/:id", (req, res) => {  
  Promise.all([
    new Promise((resolve, reject) => {
      
      // execute query
      conn.query("Delete FROM assignedcourses WHERE CourseID = ?", req.params.id, (err, result) => {
        
          if(err){
            return reject(err);
          }
        
        // query done
        resolve(result);
        
      });
      
      
    }),
    new Promise((resolve, reject) => {
      
      // execute query
      conn.query("Delete FROM courses WHERE CourseID = ?",  req.params.id, (err, results) => {
                 
          if(err){
            return reject(err);
          }
        
        // query done
        resolve(result);
        
      });
      
    }),
  ]).then((results) => {
    
    // do something with both results
    res.send(results);
    
  }).catch((err) => {
    
    // handle query errors here
    res.status(500).end(err.message);
    
  });  
});

不需要async 关键字。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    相关资源
    最近更新 更多