Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Async reduce returning promises

I have an array of objects and I have to add one property on each of the objects coming from and async function

I am doing an Array.reduce to iterate on each of the elements and return just one result: One array of objects with the new property.

I have this

const res = await resultOne.reduce(async (users = [], user, i) => {
          let userName;
          try {
            let { name } = await names.getNames(user.id);
            userName = name;
          } catch (error) {
            throw error;
          }
          delete user.id;
          users.push({ ...user, userName });
          return users;
      }, []);

But I get the message

Push is not a function of users

And this is because I think is a promise.

How can I handle async requests in a reduce or a map

like image 687
Ruben Saucedo Avatar asked Mar 14 '26 14:03

Ruben Saucedo


1 Answers

Yes, users is a promise. Don't use reduce with async functions. You could do something like await users in the first line, but that would be pretty inefficient and unidiomatic.

Use a plain loop:

const users = [];
for (const user of resultOne) {
    const { name } = await names.getNames(user.id);
    delete user.id;
    users.push({ ...user, userName: user });
}

or, in your case where you can do everything concurrently and create an array anyway, the map function together with Promise.all:

const users = await Promise.all(resultOne.map(async user => {
    const { name } = await names.getNames(user.id);
    delete user.id;
    return { ...user, userName: user };
}));
like image 101
Bergi Avatar answered Mar 17 '26 02:03

Bergi