TIL/2021–01–13
Day 32: Treehouse Full Stack JavaScript Techdegree
Today I learned about Fetch, Async/Await and Error Handling with Try and Catch
Using Fetch
ES2015 introduced a more elegant and friendlier data fetching inteface that’s native to the browser called Fetch API
Fetch uses JavaScript promises to let you handle the results returned from the server
The fetch method itself returns a promise
Also containing a response object — information about the response like the status code and the corresponding status message
In order to access and use the data from fetch() we need to parse it to JSON first
To make the fetch request:
- fetch(‘api.com’) takes on one mandatory argument — the path to the resource you want to fetch
What does the fetch() method return? A promise that resolves into a response object
Promsie.all() joins multiple individual promises into a single returned promise when all the promises resolve
— — -
Async/Await
- To further simplify how you work with promises
The word async defines an asynchronous function
Inside the async function you use the await keyword to wait for a promise
async function fetchData(url) {
const response = await fetch(url) // fetch method returns a promise, by placing await infront of fetch — the function is waiting for a resolved promise returned by fetch, once resolved, the fulfilled value returned by fetch is assigned to the variable response
Const data = await response.json() // this task is also asynchronous and returns a promise
Return data
}
Await:
- Pauses the execution of an async function and waits for the resolution of a promise then places the resolution value to the variable
- Resumes execution and returns the resolved value
- Pausing execution is not going to cause blocking behavior
- Valid only inside functions marked async
- No then methods are used because async-await lets you write asynchronous promise based code that looks like synchronous code
AN ASYNC FUNCTION ALWAYS RETURNS A PROMISE
- That promise is resolves with the value returned with the async function, or rejects it with an error thrown from within a function
- To access the data, we have to chain the then method onto the function call
— —
Convert promise handling to async/await
— — -
Combining async await with promises
An async function always returns a promise regardless if you add await or not
— — —
Error handling with try and catch
Currently our async/await functions and promise sequence do not handle exceptions and rejected promises
- Best to call catch on the rejected promise — if we don’t, the function might silently fail — like this, adding a catch on every single fetch or promise
- This will catch a rejected promise returned by the fetch call
- And we could do this with the next fetch method but it is starting to be repetitive
- We can catch all exceptions in one place by writing a separate async function that handles the fetching and parsing of data
- We can do a try catch error: the most common way to handle exceptions when using async await
Try {
All the code that needs to be executed
} catch (error){
Any code inside catch will be executed if an exception is thrown in the try block
When an error occurs, catch gets an error object containing the details about the
Error
We can use the throw statement to rethrow an exception after its caught by catch
throw error
}
What is the benefit of using async/await? You write asynchronous code in a way that resembles synchronous code
Async/await is syntactic sugar for creating functions that return and wait for promises — it’s a supplement to promises