gpt4 book ai didi

node.js - Promise.all() 不等待异步进程

转载 作者:行者123 更新时间:2023-12-04 12:17:51 45 4
gpt4 key购买 nike

在 node.js 中,我试图遍历一些项目,为每个项目完成一个异步过程,然后在下一个开始之前等待每个项目完成。我一定是做错了什么,因为 Promise.all() 没有等待任何异步进程完成!我的代码如下:

getChildLessons() {

return new Promise((resolve, reject) => {

Promise.all(

//nested for loop is needed to get all information in object / arrays
this.lessons.levels.map((item, i) => {

item.childlevels.map((childItem, iChild) => {

return ((i, iChild) => {

//return async process with Promise.resolve();
return this.horseman
.open(childItem.url)
.html()
.then((html) => {
//adding some information to an array
})
.then(() => {
return Promise.resolve();
}).catch((err) => {
reject(err);
});

})(i, iChild);

});
})

// Promise.all().then()
).then(() => {
resolve(this.lesson);
})
.catch((err) => {
console.log(err);
});
});
}

我对与 node.js 异步相当陌生,所以如果可能的话,请你提供一个清晰的例子。

最佳答案

需要解决两个问题才能使其正常工作:

  • 提供给外部 map 的回调电话没有return声明,因此结果 map创建一个数组,其中所有元素都是 undefined .您需要return child.items.map的结果,即一系列 promise 。
  • 一旦上述固定,外map将返回一个数组数组。该 2D promise 数组需要扁平化为一个简单的 promise 数组。你可以用 [].concat 来做到这一点和传播语法。

  • 所以你的代码的第一行应该变成:
    Promise.all(
    [].concat(...this.lessons.levels.map((item, i) => {
    return item.childlevels.map((childItem, iChild) => {
    添加右括号 -- 关闭 concat( 的参数列表——在适当的地方。
    其他一些说明:
  • 以下代码无用:
                  .then(() => {
    return Promise.resolve();
    })

  • promise 在哪 .then被调用根据定义在调用回调时解析。在那一刻返回已解决的 promise 不会增加任何有用的东西。返回对的 promise .then被称为就好了。你可以删除上面的 .then从链调用。
  • 快结束时你打电话 resolve(this.lesson) .这是 promise constructor anti pattern 的一个例子.你不应该创建一个新的 Promise,而是返回 Promise.all 的结果。调用,并在其内部.then来电回访this.lesson使其成为 promise 的值(value)。

  • 链接所有的 promise
    链接所有 promise 而不是使用 Promise.all , 如果您使用 async/await 是最简单的句法。像这样的东西:
    async getChildLessons() {
    for (let item of this.lessons.levels) {
    for (let childItem of item.childlevels) {
    let html = await this.horseman
    .open(childItem.url)
    .html();
    //adding some information to an array
    // ...
    }
    }
    return this.lesson;
    }

    关于node.js - Promise.all() 不等待异步进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45943964/

    45 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com