Javascript 异步/等待嵌套在循环中
我有一个基本的快速路由器。存在对数据库的异步调用以获取数据数组。然后,使用这个数组,我在循环中执行另一个异步调用。但我不知道,如何让它按照我想要的顺序工作。 代码:Javascript 异步/等待嵌套在循环中,javascript,node.js,async-await,Javascript,Node.js,Async Await,我有一个基本的快速路由器。存在对数据库的异步调用以获取数据数组。然后,使用这个数组,我在循环中执行另一个异步调用。但我不知道,如何让它按照我想要的顺序工作。 代码: const db = require('../models/index'); const router = require('express').Router(); const Op = db.Sequelize.Op; router.get('/', async function (req, res) { const dat
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;
如果您希望在处理数据集中的每个项目后打印“应始终记录”,则可以将数据集项目映射到Promise
s,然后在Promise.all()上wait
因为您正在向map
传递一个异步函数,它将返回一个Promise
,因此map
的结果是一个Promise
数组Promise.all()
返回一个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);
您希望它工作的顺序是什么?这样它就可以“从循环”n次记录,然后“最终应记录”sampleFieldCondition
可以让您运行一次findAll
并通过一次调用(例如使用或操作符)获得所有结果吗?这将有助于减少数据库的负载,加快执行速度,并可能使代码更易于阅读。不,我必须获取每个元素的数据。我希望它在循环中进行所有异步调用,循环遍历dataSet的元素,然后将这些调用的所有结果收集在一起,映射到某个数组,然后,为了能够使用这种arrayCorrect方法,@laptou-只需确保从map
调用中实际返回findAll
承诺,例如const mealQtyP=wait Promise.all(dataSet.map)(异步(项)=>{delete item.id;返回db.sequelize.models.model4.findAll({raw:true,其中:{sampleField:sampleFieldCondition}}});})//mealQtyP
是所有findAll
results@AndreiAleksandrov像这样吗?@Andreaspizza fixedno,我需要将周期中每个异步调用的结果添加到每个项中,这个周期正在迭代
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);