在使用for循环时,尝试使用async / await功能时,我真的很头疼 . 我使用的是Node.js版本:v8.6.0
简而言之,我试图从数据库中检索许多行,然后将它们全部推送到数组并返回该数组 .
我已经使用回调成功完成了这项工作,但无法弄清楚如何使用async / await .
My current code using callbacks that works
function main(db) {
gatherDates(db, function(dates) {
console.log(dates); //successful
});
}
function gatherDates(db, callback) {
const dates = [];
let today = getToday();
dates.push(today);
let dateQuery = "SELECT date FROM event_dates";
db.query(dateQuery, (err, newDates) => {
for(let row of newDates) {
dates.push(row.date);
}
callback(dates);
});
}
The code that fails trying to use async/await
async function main(db) {
let dates = await gatherDates(db);
console.log(dates); //undefined or not all of the data
}
function gatherDates(db) {
const dates = [];
let today = getToday();
dates.push(today);
let dateQuery = "SELECT date FROM event_dates";
db.query(dateQuery, (err, newDates) => {
for(let row of newDates) {
dates.push(row.date);
}
return Promise.resolve(dates);
});
}
我试图找到一个解决方案,我尝试使用多个承诺,然后在最后调用 return Promise.all(promises);
但它没有用 . 我试过 return new Promise((resolve, reject)=>resolve(dates))};
. 我查看了Promise和async / await教程和示例,这些教程和示例通常对我有用,但是当涉及循环访问我遇到问题的数据时 . 我知道我缺少一些基本的东西,所以任何帮助都会受到赞赏 . 谢谢!
2 回答
问题是你正试图从
db.query
回调which can't work内部的return
(甚至当你试图使用promise构造函数时,你在那里做了它,效果与Promise.resolve()
相同) . proper way to promisify是在外部使用new Promise
,这样你就可以从你的外部函数中return
,并且只将resolve
放在异步回调中 .您没有从异步函数中正确返回
Promise
对象,这是解决方案: