Multiple Async Requests [With React Native Example]
Lately, I was developing a “price calculator” component that uses “Google Matrix Api” to retrieve the different distances between a user’s location “A” and closest location “B” between different different constant locations “[C]”.
The problem I faced was that, in order to be able to decide what’s the location “B”, I had to check all the Distances “A” <=> “C”, and choose the minimum one, Which brings us to the topic of this article, “Multiple Async Requests”.
I faced this scenario so many times before, that’s why I decided to share this post about how I’m solving it, maybe it will be helpful for other developers who are facing a similar issue.
This problem has two solutions, the use of Promise.all() [Not the focus of this post], or the use of another magic word, we will discover together.
First, let’s build together a small “Button” component that once clicked will show a “loading…” text, and will show the“result” after all the “calculation” has finished.
Now, let’s build our “callFunction” together.
We said we have a collection of “C “ items, for each item of this list we will make a Request, and compare its result [currentResult] with the available minimum result [minResult].
The above code assumes that all the GET requests will be called one after the other (sequentially), so much fast that it will not collide with the next call. In real life scenario, that’s totally wrong, actually most of the time this function will finish execution before we get the response of the first GET request.
How to fix that ? Just by telling our code when to WAIT and when to continue execution.
But, before start using our new cool keyword , there’s something else you should know also!
awaitworks only inside
asyncfunctions, and it’s pretty cool.
So, basically we need just to add “async” keyword to our function.
Another problem, the “await” keyword will be added inside the “foreach” function and not our “callFunction”. And the current “foreach” function is not really useful in this scenario (You can check this article on how to make “foreach ”returns a Promise).
So, i’ll just re-write the above code to be as the following:
What I like more about the “async” functions, is that they returns a Promise. So, if you want to use the “callFunction” from another function, you can do that without worrying about any “async” related issues anymore:
In the beginning of this post, I mentioned that there’s another solution to this problem: “Promise.all()”, I didn’t talk about it here, but we can resume the difference between the two solutions with the following tweet (or thread if you follow the tweet link).
I hope this article added something to you, and please feel free if you have any comment or question to write down. Cheers!
[You can check also]: