簡體   English   中英

如何正確使用 Promise.all() 和 then() 與異步函數?

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

在下面的代碼中,我試圖將第一個和第二個查詢的結果放在一個名為result的全局變量中。 問題是Promise.all()沒有等待查詢完成並在繼續then()

我該如何解決?

代碼:

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");
});

輸出:

result
query 1
query 2

就像評論中所說的那樣,您需要手動承諾異步調用:

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

或首選方法是使用像bluebird這樣的庫:

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

並且您的代碼可以修改為:

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));

謝謝大家! 就像大家說的,問題出在Promise.all()中的錯誤參數中。 這是修改后的代碼。

代碼:

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