简体   繁体   English

如何正确使用 Promise.all() 和 then() 与异步函数?

[英]How to properly use Promise.all() and then() with async functions?

In the following code, I am trying to put the results from the first and second query inside a global variable called result .在下面的代码中,我试图将第一个和第二个查询的结果放在一个名为result的全局变量中。 The problem is Promise.all() is not waiting the queries finish and before proceding to then() .问题是Promise.all()没有等待查询完成并在继续then()

How can I solve it?我该如何解决?

Code:代码:

var result = {};
Promise.all([
  connection.query('SELECT * FROM analysis', 
    function(err, rows, fields) {
      if (err) throw err;
      result.analysis = rows;
      console.log("query 1");
  }), 
  connection.query('SELECT * FROM analysis_description', 
    function(err, rows, fields) {
      if (err) throw err;
      result.analysis_description = rows;
      console.log("query 2");
  })
])
.then(function(result){
  console.log(result);
  console.log("result");
});

Output:输出:

result
query 1
query 2

like said in the comments, you need to promisify the async calls, either manually:就像评论中所说的那样,您需要手动承诺异步调用:

queryAsync = query => new Promise((resolve, reject) => {
  connection.query(query, (err, rows) => {
    if(err) return reject(err)
    resolve(rows)
  })
})

or preferred way is using library like bluebird :或首选方法是使用像bluebird这样的库:

connection  = require('bluebird').promisifyAll(connection)

and your code can be modified into:并且您的代码可以修改为:

var result = {};
Promise.all([
  connection.queryAsync('SELECT * FROM analysis').then(rows => result.analysis = rows), 
  connection.queryAsync('SELECT * FROM analysis_description').then(rows => result.analysis_description = rows)
]).then(function(result){
  console.log(result);
  console.log("result");
}).catch(e => console.error(e));

Thanks, everyone!谢谢大家! Like everyone said, the problem were in the wrong parameter in Promise.all() .就像大家说的,问题出在Promise.all()中的错误参数中。 This is the code after the changes.这是修改后的代码。

Code:代码:

Promise.promisifyAll(require("mysql/lib/Connection").prototype)

var result = {};
Promise.all([
  connection.queryAsync('SELECT * FROM analysis')
  .then(function(rows){
    console.log(rows);
    result.analysis = rows;
  }), 
  connection.queryAsync('SELECT * FROM analysis_description')
  .then(function(rows){
    result.analysis_description = rows;
  })
])
.then(function(){
  console.log(result);
  console.log("result");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM