[英]async/await nested in cycle
我有一个基本的快速路由器。 有一个对数据库的异步调用来获取数据数组。 然后,使用这个数组,我正在循环中进行另一个异步调用。 但我不知道如何让它按照我想要的顺序工作。 代码:
const db = require('../models/index');
const router = require('express').Router();
const Op = db.Sequelize.Op;
router.get('/', async function (req, res) {
const dataSet = await db.sequelize.models.model1.findAll({
raw: true,
include: [{
model: db.sequelize.models.model2,
}, {
model: db.sequelize.models.model3,
required: true
}],
limit: 10,
order: ['flight_date']
});
dataSet.forEach(async (item) => {
delete item.id;
const mealQtyP = await db.sequelize.models.model4.findAll({
raw: true,
where: {
sampleField: sampleFieldCondition,
}
});
console.log('from cycle'); //but it logged after "shall log after all"
});
console.log('shall log after all'); //want it to be logged after all
});
module.exports = router;
如果您希望在处理完dataSet
每个项目后打印“shall log after all”,您可以将数据集项目映射到Promise
,然后在Promise.all()
上await
。
await Promise.all(dataSet.map(async (item) => {
delete item.id;
const mealQtyP = await db.sequelize.models.model4.findAll({
raw: true,
where: {
sampleField: sampleFieldCondition,
}
});
console.log('from cycle'); //but it logged after "shall log after all"
}));
console.log('shall log after all'); //want it to be logged after all
因为你将一个异步函数传递给map
,它会返回一个Promise
,所以map
的结果是一个Promise
的数组。 Promise.all()
返回一个Promise
,当数组中的所有原始Promise
都被解决时,该Promise
被解决; 因此,等待这个Promise
将等到dataSet
每个项目都被处理。
修改此代码以实际为您提供结果:
const results = await Promise.all(dataSet.map(async (item) => {
console.log('from cycle'); //but it logged after "shall log after all"
delete item.id;
return db.sequelize.models.model4.findAll({
raw: true,
where: {
sampleField: sampleFieldCondition,
}
});
}));
console.log('shall log after all'); //want it to be logged after all
console.log('here are my results:', results);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.