Tuesday and Making Fetch Happen
…continuing from yesterday, my notes from doing Vanilla JS Academy class of October 2021.
Promises
Promise
is an object that represents an asynchronous functionPromise.resolve()
is a method that will return a Promise object that is resolved- and similarly
Promise.reject()
will return one that is rejected Promise.then()
can attach functions to run when the Promise resolvesPromise.catch()
is a method to detect and do something about failure
You can chain multiple Promise.then() methods together, and they’ll run in sequence. Whatever you return from the current Promise.then() method gets passed along to the next Promise.then() method after it in the chain.
Using Promises is a guide that describes “Since most people are consumers of already-created promises, this guide will explain consumption of returned promises before explaining how to create them.” Yes! I am probably going to consume promises a whole lot, which segues nicely into:
Fetching resources 🤹🏻
Calling an API or fetching a remote file from a server. Why it’s helpful to understand promises:
The fetch() method returns a Promise. We can handle API responses chaining Promise.then() and Promise.catch() methods to it. Let’s pass the response object into our Promise.then() callback function, and log it to the console:
// Basic window.fetch() syntax example from Vanilla JS Academy
fetch("https://jsonplaceholder.typicode.com/posts")
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.warn(error);
});
setTimeout()
A piece of code that explains itself nicely; it will set a timeout. But now I also understand what it is and where it comes from. setTimeout() is a global method that I find directly under Web APIs in the list of interfaces which are “all the interfaces (that is, types of objects) that are available.”
Core JS vs stuff built into browsers
I had a decent enough mental model of how JavaScript the language and the Web APIs are two different things. But nevertheless something just clicked in my brain on a new level here. Navigating docs will be a tad more straight forward for me moving on. Also found this text on MDN with JavaScript technologies overview that I’ve not come across before.
Standard built-in objects
Everything from NaN
to Date
but also Promise
comes from the core language (ECMAScript).
Web APIs (and interfaces)
The DOM itself is a web API, where for example Element
is an interface. setTimeout()
is another.
There is a Fetch API with fetch()
as an interface, a method that is available when I am working in a web context. And aaaaa-hahahaha 🤯😂 now I get how the npm package node-fetch
that I’ve bumped into a lot in our apps is adding fetch to node because it’s not available there.
I recently tried reading The Fetch API is finally coming to Node.js, all the way back in last week when I did’t understand that post — but now today it’s totally readable to me. 💥
Array methods
More yay, because working with arrays is something I practiced a lot in C when doing CS50 last year. There are definitely JS specifics to pick up, but this is not the stuff that will fry my brain.
Array.push()
to add items to an arrayArray.slice()
to copy a segment to a new arrayArray.shift()
to remove first item (and modify original)Array.pop()
to remove last item (and modify original)Array.includes()
returns true/false if item exists in arrayArray.map()
to create a new array from calling a function on every element in the initial arrayArray.join()
will concatenate elements in an array and return a new stringArray.find()
to grab first item that meets a condition
async/await
async
and await
are operators. Wait, what? This complete list of expressions and operators categorize them as primary expressions like array initializer []
or grouping operator ( )
. The other categories are for example arithmetic, relational, equality, and so on. Ok, got it.
When you use the async operator before a function, you turn it into an async function. Inside an async function, you can use the await operator before asynchronous code to tell the function to wait for that operation to complete before moving on.
So I think they belong together? Yup, kinda. MDN describes that:
The await operator is used to wait for a Promise. It can only be used inside an async function within regular JavaScript code; however it can be used on its own with JavaScript modules.
try...catch
A statement in the category control flow, just like if...else
and switch
.
Because an async function always returns a promise, we can chain a Promise.catch() method to it. That works, but many developers prefer to use a try...catch block inside their async function instead.
Convert traditional chained promises to async/await was the final step of the quotes project.
const endpoint = "https://ron-swanson-quotes.herokuapp.com/v2/quotes";
async function getQuote() {
try {
const response = await fetch(endpoint);
if (!response.ok) {
throw response.status;
}
const data = await response.json();
//
// do stuff with the data here
//
} catch (error) {
// error handling here
}
}
It’s been a couple of months since this particular project in the course. Really cool to see how revisiting the videos and diving into everything to write up these notes today has made substantial chuncks of javascript just snap into place in my brain. 🔥
Related content to study more another day
- Using Promises guide on MDN, especially the part on Common mistakes
- We have a problem with promises by Nolan Lawson