如何在异步函数中正确使用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");
});
相关文章:
- 如何在异步函数中正确使用Promise.all()和then()
- promise.all在一个forEach循环中——所有东西都同时启动
- 如何将Promise.all与其他Promise.all
- 运行Promise.all()中的When-is-then-then子句
- Promise和Promise.all(数组)在数组实现之前执行
- promise.all只返回第一个数据
- Node.js中的Promise.all没有't调用then函数
- Promise.all()方法没有't解析为一个值
- 如何正确解析和使用promise.all()
- Promise.all() - 在触发多个事件侦听器后执行某些操作
- 为什么 Promise.all(array) 没有立即解决
- Promise.all:解析值的顺序
- RXJS5 vs Promise.all
- 对象文字(哈希)与 Promise.all
- ES6 Promise.all() promise 数组的奇怪分辨率
- Promise.all behavior with RxJS Observables?
- Promise.all() - 如何在不返回 undefined 或 value 的情况下解析()
- 为什么在 Promise.all() 之后没有调用 onJect,其中数组中包含的 Promise.reject() 传
- Promise.all 不应该作为传递给 .then 的函数工作
- Promise.all() 解析,但它不应该(node.js)