我有3个总的forEach循环,我希望前两个等待承诺的然后块执行之前,他们重新开始和迭代。我已经用console.log语句证明了这一点,分别标记为1,2和3.如何在循环再次迭代之前等待承诺的“then”块在嵌套的forEach循环中执行?
我想要控制台日志按顺序排列,如“1,2,3,1,2,3等” 而是我得到的是“1,2,1,2,1,2,1,2,1,2,3,3,3,3,3,3” 我如何使这一切顺序? fetchCandidatesByCity是mongoose find方法,它返回一个promise。
axios.get(FEED_URL).then(data => {
let candidatesWithMessageSent = [];
data.data.jobs.forEach(job => {
console.log("1");
// console.log(candidatesWithMessageSent);
job.city.forEach(cityAndState => {
console.log("2");
let jobState = extractState(cityAndState);
let jobLocation = addSpaceAfterComma(cityAndState.toLowerCase());
let jobCity = extractCity(jobLocation);
fetchCandidatesByCity(jobCity)
.then(candidates => {
candidates.forEach((candidate, index) => {
console.log("3");
const candidateId = candidate._id.toString();
if (index <= MAX_MESSAGE_LIMIT &&
!containsUberLyft(job.title) &&
priceIsHigh(job.price) &&
!candidateHasMessage(candidatesWithMessageSent, candidateId)) {
const jobURL = `http://www.jobs2careers.com/click.php?id=${job.id}.${PUBLISHER_ID}`;
// candidate has received a job notification, so add candidate to candidatesWithMessageSent
candidatesWithMessageSent = [ ...candidatesWithMessageSent, candidateId ];
}
return;
});
})
.catch((error) => {
console.log(error);
});
});
});
});
您的示例代码从不使用'data'和'pieceOfData'。这是否代表您询问的实际情况,还是实际使用它们?如果是后者,你需要展示他们将如何使用。 – cybersam
该函数本身很长,但我可以展示它。此示例代码是缩写版本。 – Mjuice
你想要处理所有异步操作的结果是确定哪种解决方案效果最好的重要组成部分,因此我们需要更多关于循环和你想要做什么的细节。 – jfriend00