Whatever is rendered here is what's going to show up inside the app. But we're turning it up to 11. That's pretty simple. Most apps are a lot more complicated than that. I see on the Hydrogen team hundreds of different apps that are built out that do some wild stuff inside their loaders.
So let's consider what might be a little bit more advanced, what might be happening. So inside our loader, maybe we're going to load some products, then maybe we're going to load some reviews, then maybe we might load recommendations. And after that, we might also load in the logged in user to display something about who's logged in. That's great. This code actually looks really, really nice. It's really simple. It's easy to understand. Load this, then this, then this. Looks awesome.
But actually, there's a serious problem with this code. Specifically, it's called what is a waterfall. A waterfall is where we have to load one thing, and it's not until that finishes loading, then we can proceed to load the next thing. So essentially, we're doing nothing in parallel. We're loading one, then the other, then the other, then the other. So this is four times slower than it needs to be. And the easiest way to solve this is just wrap everything in promise.all.
If you wrap everything in promise.all, now there's one await at the top, and we load everything in parallel, so now the waterfall is flat. There's not any waiting on anything, and once everything's done, we can render the UI. But if I'm frank, this isn't as intuitive as this. Like this whole promise.all thing, it's kind of unfortunate JavaScript, I feel like, the primitives that we have, this just doesn't look as nice to a lot of developers, and a lot of developers, I feel like, would rather see something like this.
And the key here, though, is if you ever have more than one await in an async function, not even just in Remix, just in any async function in JavaScript, if you have more than one await, you have a waterfall. Maybe that waterfall is necessary. Maybe it's But if you have more than one await, something is processing, you're waiting for it to finish, and then something else is going to process after it. So if you ever see more than one await in a single async function, maybe you should consider looking at it, talking through is that necessary, could it be parallelized? But again, we're tearing this up to 11, it can be, it's not always this complicated. It's not always so easy just to parallelize everything in the function.
Comments