Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through an array via an async function inside another async function?

I am trying to call two apis with two async function.The thing is that the second
async function's api call depends upon the the result of the first async function.

  1. My first async function fetches some data from an api and returns an
    array(users) of objects .
  2. The second async function calls another api that takes the id property from
    each object of users as url parameter.and will returns a status for each
    object and we want to filter only those user that has status 204.

I know the logic on how to do this but can't implement it in real world.Plus
nested async functions always seems hard to me , here is my attempt :

    const getUsers = async () => {
        const { users } = await axios.get(url);
        return users;
    };

    const getCheckedUsers = async () => {
        const allUsers = await getUsers();
        const promises = allUsers.then(users => {
            users.map(async user => {
                const { status } = await axios.get(another_url_that_takes_`user.id`);
                if (status === "204") {
                    return user;
                }
            });
        });
        const results = await Promise.all(promises);
        return results;
    }

First function works fine i tested it separately.It returns the needed array.
But the issue starts when i try to combine first async function with the second
one.

like image 739
rocktimsaikia Avatar asked Oct 23 '25 19:10

rocktimsaikia


1 Answers

Using async/await there's no need to get lost with Promises since the code just runs line by line:

const getUsers = async () => {
  const { users } = await axios.get(url);
  return users;
};

const getCheckedUsers = async () => {
  const allUsers = await getUsers();
  const results = [];
  for (user of allUsers) {
    const { status } = await axios.get(`another_url_that_takes_${user.id}`);
    if (status === "204") {
      results.push(user);
    }
  }
  return results;
}
like image 55
Erick Petrucelli Avatar answered Oct 25 '25 08:10

Erick Petrucelli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!