0

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

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

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问题:一个接一个地解决承诺(即按顺序)?

4

2 回答 2

1

activityPlace is still just a promise you will need to await

console.log(await activityPlaces);

Note that you're not doing anything with the result of each promise (aside from the last one)

Wouldn't it be way easier to just throw this in a regular for loop and await one by one? the reduce pattern is useful for cases where you don't have async/await, but you don't seem to have this limitation:

const results = [];

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

console.log(result);

The above code matches the behavior of your first sample.

于 2020-10-25T20:55:43.057 回答
-1

看起来您正试图避免使用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));

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

于 2020-10-25T21:00:02.920 回答