I have very basic async function going on here. my primary function "formatData" is formatting some data from an array "arr" . which are basically some github usernames.
Very basic . But the issue is to get the followers count i created another async function "getFollowers" which extracts the followers count with given argument which is the github user name that i am providing in formatData.
But the function returns the empty array "result" before the "getFollowers" is resolved.
So basically i want the whole array map loop to resolve before it reaches to return the empty array. What am i missing here ?
that’s not how you use map, it’s not just a different syntax for a loop.
the format function is synchronous, and what is in it is subject to normal JS rules: arr is declared, result is declared. You declare you’re going to do some async operation. In the meantime, result is returned (and it’s an empty array).
Promise.all is generally what you want in this case though, code would be similar to above but the requests will happen basically all at once rather than sequentially.
@DanCouper, you don’t need that first await though… @RocktimSaikia, as @DanCouper, pointed out, you need to make an array of promises and:
either pass it like that, then any expecting party would have to const users = await Promise.all(response);
or make your formatData an async and return await Promise.all(result);
You can choose either way (2nd preferably), but the key here is to have array of promises, whereas in your first example promise is nested inside object…