我得到了由sequelize.findAndCountAll()返回的promise对象,我想在映射它们之前过滤该对象。
这是我的代码:
async function getCountTask(id){
return await Tasks.count({
where: {
studentID: id,
status: 'Done',
grade: ['A', 'B']
}
});
}
let totalStudent = [];
await Promise.all(
listStudent.filter(async (f) => {
const count = await getCountTask(f.id);
if(count <= 3){
return false;
}
return true;
}).map(async (e) => {
let obj = {};
obj.id = e.id;
obj.age = e.age;
obj.status = 'Great';
totalStudent.push(obj);
})
)
我期望listStudent包含5个数据,但是经过过滤后,它只会包含3个数据,因为另外2个没有通过条件。因此,对于最终结果,totalStudent 包含 3 个数据。
但是我从上面的代码中得到的是,totalStudent 的数据与listStudent 完全相同。 因为它先处理map,再处理filter,所以map处理的是还没有过滤的数据。
如何让它先成为过滤器,然后映射数据。
提前致谢。
最佳答案
过滤器/ map 等,不支持您使用它们的方式异步
。
async
函数始终是一个 promise 。
await Promise.all(
listStudent.filter(async (f) => { <<<<---- This makes filter always return true
const count = await getCountTask(f.id);
看看你的代码,一个简单的解决方案就是删除过滤器,然后使用 map ..
例如..
await Promise.all(
listStudent.map(async (f) => {
const count = await getCountTask(f.id);
if (count <= 3) return; //don't want this one.
let obj = {};
obj.id = f.id;
obj.age = f.age;
obj.status = 'Great';
totalStudent.push(obj);
})
)
由于Promise.all
返回一个数组,您还可以避免在totalStudent
上使用push
。
例如。
totalStudent = await Promise.all(
listStudent.map(async (f) => {
const count = await getCountTask(f.id);
if (count <= 3) return; //don't want this one.
let obj = {};
obj.id = f.id;
obj.age = f.age;
obj.status = 'Great';
return obj;
})
)
上面的好处是还保持了返回顺序。
关于javascript - 使用异步过滤和映射 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60525586/