Using `Promise.all` to make your app load quicker
If you use React (or others) for an app that calls a db for data, you will likely already know to use
In fact, I was using
await regularly in everyhour.xyz as it is so simple, easy and readable.But there was one page specifically that was awful for loading especially with the most heavy users — including myself.
everyhour - the honest way to track your time and progress
Struggling with time? everyhour helps you easily record what you do - motivating you to not waste time, prioritise what…
In short, this page was showing analytics of users record time. We need to load the page content, call 8 different apis for data, parse this data into different graphical formats and then display.
Thankfully, most of this was relatively quick, but the API calls were slow:
The user with the most recorded time (me… as I have been recording time for three years) was experiencing over 10 seconds of loading time.
How does await work?
As the name suggests, by stating await we pause all further processing. This is great as then I can retrieve data, pause, and then use that data immediately!
Where it comes a problem is where I over user it. Stating 8 different awaits adds a serious amount of time lag. Each one has to wait for the next one as you can see in the plot.
The longest call in there takes around 2 seconds.
Why don’t parallise these?
Exactly. And it is brilliantly simple:
await doSomethingElse();AFTERawait Promise.all([
That is it!
Interestingly unexpected. The longest calls before took around 2 seconds. Now they take almost 4 seconds!! This means all the data is retrieved in the time it took two too!
Looking at the inboard stats on my database, this longer processing time is because we are giving it a lot more work to do with the same number of resources and hence it can be slower.
But for users, this is much better.
I also changed the app to load incrementally which means the delay is less than a second which makes time to content much shorter and hence the value they get back more meaningful!
I hope this helps! Follow me to see more of this type of content as I continue to learn!