Svelte

Svelte Asynchronous await Blocks

Topics:

This course has been updated! We now recommend you take the Svelte Fundamentals course.

Check out a free preview of the full Svelte course:
The "Asynchronous await Blocks" Lesson is part of the full, Svelte course featured in this preview video. Here's what you'd learn in this lesson:

Rich demonstrates asynchronous data and being able to render the results of a promise into a component using await blocks.

Get Unlimited Access Now

Transcript from the "Asynchronous await Blocks" Lesson

[00:00:00]
>> Very often when you're building web applications, you will need to deal with asynchronous values. That is to say you're fetching some data over the network and it's represented as a promise. And that's often quite difficult inside templates. So Svelte introduces something called the await block, which is a way of handling promises natively, right inside your template markup.

[00:00:23] So here we have a promise which is getting a random number from this API end-point. It gets the number and then it resolves the fetch and then if the response was okay it returns the value of the API response. And if it didn't work for whatever reason, which sometimes it doesn't, because this endpoint is programmed in such a way that it will occasionally fail just to demonstrate the point that we're making, it will throw an error instead.

[00:00:56] So we can have a promise that can resolve or reject. And whenever we click this button is gonna get us a new random number. So we're right now, we're just putting the promise right there on a template and it's showing up as an object promise string, which is not very helpful.

[00:01:14] We're gonna replace that with the await block. So far we've got the waiting section so this is when the promise is still pending. This is what is visible. When we've got the value that we want, we pass it to the then close of your await block. All right, so you'll see what happened there.

[00:02:01] It went away to get the data took a little while to come back, but when it did resolve, it prints the number to the screen, generate another one. It's gonna wait a little bit and then it's going to print the number to the screen. Sometimes it will go wrong.

[00:02:14] So we need to have a catch clause as well. And inside the catch clause we have access to an error and if that happens Will print the error message to the screen. I don't have time to keep taking us back for when that happens, so what I'm gonna do is.

[00:02:37] Gonna open my data tools and turn everything offline. So now in theory, when I click generate random number is gonna give us an error, fail to fetch. Okay, so this is a really easy way of structuring code that needs to deal with asynchronous values.