需要帮助,我遇到问题数组保持为空从forEach中推入对象后,我会错过吗?这是代码:
const allStatus = [];
result.forEach(async (element) => {
const count = await BpCandidate.count({
where: {
applicationStatusId: element.id
},
raw: true,
});
})
record = {
id: element.id,
name: element.name,
code: element.code,
description: element.description,
total: count
};
allStatus.push(record);
});
console.log(allStatus);
预先感谢
答案 0 :(得分:1)
使用for...of
对您有用,但是如果您使用Promise.all
const allStatus = await Promise.all(result.map(async (element) => {
const count = await BpCandidate.count({
where: {
applicationStatusId: element.id
},
raw: true,
});
return {
id: element.id,
name: element.name,
code: element.code,
description: element.description,
total: count
};
}))
答案 1 :(得分:0)
首先,您需要在foreach部件的外部范围内定义element
变量以获得所需的结果,这是帮助程序代码段:
const allStatus = [];
result.forEach(async (element) => {
const count = await BpCandidate.count({
where: {
applicationStatusId: element.id
},
raw: true,
});
record = {
id: element.id,
name: element.name,
code: element.code,
description: element.description,
total: count
};
allStatus.push(record);
})
});
console.log(allStatus);
答案 2 :(得分:0)
都不会执行异步任务,也不会解决诺言。 用于of或Promise。所有循环迭代。
const allStatus = [];
for(let element of result) {
const count = await BpCandidate.count({
where: {
applicationStatusId: element.id
},
raw: true,
});
})
record = {
id: element.id,
name: element.name,
code: element.code,
description: element.description,
total: count
};
allStatus.push(record);
});
console.log(allStatus);