我知道js中的循环不会等待异步过程,因此,当异步过程完成时,循环将始终处于最后一次迭代。
我的问题是,如何解决这个问题,以便我可以让 for 循环等待循环的每次迭代?
getChildItems() {
return new Promise((resolve, reject) => {
this.lessons.levels.map((item, i) => {
item.childlevels.map((childItem, iChild) => {
((i, iChild) => {
this.horseman
.open(childItem.url)
.html()
.then((html) => {
cheerio(html).find('.list-item a').map((index, elem) => {
let lesson = cheerio(elem);
childItem.lessons.push(
{name: lesson.text(), url: lesson.attr('href')}
);
});
})
.then(() => {
const outter = i >= this.lessons.levels.length - 1;
const inner = iChild >= item.childlevels.length - 1;
if (outter && inner) {
resolve(this.lessons);
}
});
})(i, iChild);
});
});
});
}
最佳答案
将异步调用放入循环中是一种不好的做法。您有两种方法来处理这个问题。
<小时/>1 - 您希望并行调用函数
使用Promise.all。例如:
const rets = await Promise.all(this.lessons.levels.map(...));
<小时/>
2 - 您希望函数被依次调用
关于javascript - 在 Node.js、es6 中,如何让循环等待异步进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45915914/