0

If I have a function that gets an api response and awaits it, like this:

async function getResponse(repo) {
  const apiResponse = await axios.get(...); // uses repo
  return apiResponse;
}

and I have a function that applies this function to many repos:

async function getResponsesMany(repos) {
  const promises = [];
  repos.forEach(repo => promises.push(getResponse(repo));
  const responses = await Promise.all(promises);
  return responses;
}

I can get all my data like this:

const allData = await getResponsesMany(myRepos);

But this is weird to me, because getResponse is awaiting the axios.get call, but I feel like I don't need to do that, since when I await Promise.all(promises) it will handle any nested promises. Am I supposed to therefore refactor getResponse to return the promise returned by axios.get instead? Is there a reason one should be faster than the other?

713sean
  • 313
  • 11
  • 3
    There's no point `await`ing in `getResponse` as written, no. Fundamentally it still returns a promise of the result of calling `axios.get`, as calling `axios.get` already does, so you could just `return axios.get(...)` (and then it doesn't even need to be `async`). Also it's unnecessary to create an empty array, push a bunch of promises into it then `await` the result - just `await Promise.all(repos.map(...))`. – jonrsharpe Apr 24 '23 at 21:55
  • thanks feel free to leave a response and I can accept it. – 713sean Apr 24 '23 at 22:03
  • `nested promises`, there are no nested promises here, just a list of promises.. Nested would imply the result of previous promises are required for deeper ones.. – Keith Apr 24 '23 at 22:11
  • `getResponsesMany` returns a promise containing promises, no? – 713sean Apr 24 '23 at 22:12
  • Well yes, that's how promises work, and why you see the term promise chain. The term nesting maybe threw me.. – Keith Apr 24 '23 at 22:16
  • I think I understand what you're saying, and I was using nesting in a more uncommon way / not what is normally used – 713sean Apr 24 '23 at 22:18
  • Arguably you don't even have to await the Promise.all, just return it since you need to await `getResponsesMany` anyway. – pilchard Apr 24 '23 at 22:22
  • right, I see, I'm starting to see the pattern of how to use them now, thanks – 713sean Apr 24 '23 at 22:23
  • @Keith technically since `getResponse` is an `async` function, omitting the `await` makes the returned promise be resolved with the axios promise, which you might consider "nesting". One could however drop the `async` marker when there's no `await` left in the function :-) – Bergi Apr 24 '23 at 22:56
  • @713sean No, `getResponsesMany` does not return a promise containing promises. It returns a promise for an array of values. – Bergi Apr 24 '23 at 22:56

0 Answers0