【问题标题】:Trouble with resolving promises in sequence按顺序解决承诺的麻烦
【发布时间】:2020-10-27 00:55:21
【问题描述】:

由于在使用 Promise.all 时遇到网络错误,我正在尝试在 NextJS 应用程序的构建过程中解决一系列承诺,但由于某种原因,我无法解决这些承诺。

此代码有效,但不适用于我的构建:

const activityPlacesPromises = activityLocationIDs.map((id) =>
    this.get(`places/${id}`)
);

const activityPlaces = await Promise.all(activityPlacesPromises);

console.log(activityPlaces); // Returns the data correctly

此代码不起作用:

const activityPlaces = activityLocationIDs.reduce((promise, id) => {
    return promise.then(() => this.get(`places/${id}`));
}, Promise.resolve());

console.log(activityPlaces); // Returns Promise { <pending> }

为什么 Promise.resolve() reduce 函数不起作用?

PS:我要结束这个 SO 问题:Resolve promises one after another (i.e. in sequence)?

【问题讨论】:

  • 只是const result = await activityPlaces。因为那时它只是promise.then 的链,所以它仍然是一个承诺,而不是一个结果。

标签: javascript promise


【解决方案1】:

activityPlace 仍然只是一个你需要等待的承诺

console.log(await activityPlaces);

请注意,您没有对每个承诺的结果做任何事情(除了最后一个)

将其放入常规的 for 循环中并一个一个地等待不是更容易吗? reduce 模式对于您没有 async/await 的情况很有用,但您似乎没有此限制:

const results = [];

for(const id of activityLocationIDs) {
  results.push(await this.get(`places/${id}`));
}

console.log(result);

以上代码与您的第一个示例的行为相匹配。

【讨论】:

  • 啊,好吧,我没有意识到 reduce 模式适用于无法使用 async/await 的环境。你的例子很好用,谢谢。
【解决方案2】:

看起来您正在尝试避免使用async/await,首先也许您应该捕获任何错误,以允许继续记录和执行:

const activityPlaces = activityLocationIDs.reduce((promise, id) => {
    return promise
        .then(() => this.get(`places/${id}`))
        .catch((err) => console.error(`Error getting place ID: ${id}`, err))
}, Promise.resolve());

activityPlaces.then(() => console.log(activityPlaces));

另外,考虑到由于您的代码不再使用异步,您的构建可能不会在结束前等待 Promise 解决。

【讨论】:

    猜你喜欢
    • 2021-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-12
    • 1970-01-01
    • 2017-04-20
    • 2019-10-23
    相关资源
    最近更新 更多