0

I'm trying to resolve an array of promises in the build process of a NextJS app since I'm getting network errors when using Promise.all, but for some reason I'm having trouble resolving the promises.

This code works, but does not work with my build:

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

const activityPlaces = await Promise.all(activityPlacesPromises);

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

This code does not work:

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

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

Why isn't the Promise.resolve() reduce function working?

PS: I am going off of this SO question: Resolve promises one after another (i.e. in sequence)?

FRMR
  • 289
  • 3
  • 27
  • just `const result = await activityPlaces`. Because at that point it's just a chain of `promise.then` so it's still a promise, not a result. – Sheraff Oct 25 '20 at 21:07

2 Answers2

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.

Evert
  • 93,428
  • 18
  • 118
  • 189
  • Ah, okay I didn't realize the reduce pattern was for environments where you couldn't use async/await. Your example works nicely, thank you. – FRMR Oct 25 '20 at 21:00
-1

It looks like you are trying to avoid using async/await, firstly perhaps you should catch any errors, to allow logging and execution to continue:

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));

Also, consider that since your code is no longer using async, your build may not wait for the promises to resolve before ending.

gunwin
  • 4,578
  • 5
  • 37
  • 59