Now, we should have more than enough info to understand how JavaScript handles asynchronous functions. So beyond creating a setTimeout
, what can we do with them?
Well, that's where calling an "API" comes in!
API → Application Programming Interface
Basically, it's an interface your frontend can interact with in order to get some data. This interface is exposed via "endpoints," which are the channels that this data will pass. You can view them just like functions in JavaScript, where they accept some input parameters and return an expected output.
For example, say we're interacting with the Twitter API, and we want to get some information about our personal profile. For this, we would need to use an API endpoint that takes in your user ID and returns the data about that user. This would likely be a "get" endpoint, since we're trying to get information from Twitter into our website.
To understand APIs a little better, it's worth explaining the difference between a "server" and a "client." Up until now, all of the websites we've been writing have been frontend, client-side applications.
Since server applications aren't being run locally, we need to talk to them over the Internet in order to get information they have stored. However, once we request something, we have no clue how long the server will take trying to get and return that information.
This is why we need asynchronous functions! That way, we can keep running our JavaScript as normal. Once the server gets back to us, we can execute our asynchronous callback to handle the result.
When talking to an API, you need to speak the language of the Internet. HTTP request types specify how to format your API requests so the API knows whether you’re putting info in, getting info out, or updating existing data.
GET
→ request to retrieve data from a particular source. This can have parameters specifying further information about what you want (ex. a user's ID)POST
→ request to submit data to a particular destination. The API sees this data and handles updating whatever resources it needs to update (ex. sending a new post to a Reddit timeline)PUT
→ request to post an entire file, overwriting what is there if necessary. This is similar to post
, though it is very rarely used. More about PUTNow that we know a little about what APIs are, let's try talking to one ourselves.