【发布时间】:2018-02-05 12:59:29
【问题描述】:
我知道 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);
});
});
});
}
【问题讨论】:
-
你能简化代码吗?有点难以理解你想用代码实现什么。
-
在循环中等待异步结果绝非易事……您想在两个 .map 中的哪一个中执行此操作?
标签: javascript node.js asynchronous async.js