Examples
-
Introduction
- Synchronous
a) We wait for a function to finish its work, and then do something with the result.
b) One statement is processed after the other, line by line, in a single thread in the JS engine.
- Asynchronous
a) We let that function do its job in the background, so that we can move on with the code execution.
b) We pass in callback functions that run once the function has finished its work.
As we can see on the example below, the setTimeout function receives 2s as a callback function, so it will run the function and when its done, in 2s it will print it to the console.
c) Callback function: accessible by another function, is invoked after the first function if that first function completes. - Examples
Synchronous: Logs: 'Hey there', 'Second', 'The end'.
Asynchronous: Logs: 'Hey there', calls second() and returns to first(), 'The end', 2s after calling second() it prints 'Second' in the console.
* This will not make the code stop for two seconds. The second function returns and goes back to the first function, printing out 'The end' to the console and then when the 2s finishes, it prints 'Second'. - Event Loop
1) first() goes to the EXECUTION CONTEXT and runs.
2) log() goes to the EXECUTION CONTEXT and logs 'Hey There', then the function retuns and pops log() out of the EXECUTION CONTEXT.
3) second() goes to the EXECUTION CONTEXT.
4) setTimeout goes to the EXECUTION CONTEXT, as this is part of the WEB APIS, that is where the timer will be running for 2s asynchronously, together with the callback function, while the code will continue executing.
5) the setTimeout function returns, as it's now in the WEB APIS and not at the EXECUTION STACK and so does second(), being that it was only there to execute setTimeout().
6) log() goes to the EXECUTION CONTEXT and logs 'The end', then it returns and goes out of the EXECUTION CONTEXT.
7) As first() has now finished execution, it will pop out the EXECUTION STACK, leaving it empty.
8) When the 2s finishes, the callback function will pass into the MESSAGE QUEUE area.
9) As soon as the EXECUTION STACK is empty, the EVENT LOOP will push the callback function into the EXECUTION STACK (same happens to DOM events). This is what the EVENT LOOP does.
10) A new EXECUTION CONTEXT will be created for the callback function.
11) Now the setTimeout function will be executued, so it will create a new Execution Context for the log() and print 'Async Hey there!'.
12) Now, if there were more callback functions waiting, like data coming back from a AJAX request or the handler of a DOM event, then the event will continue pushing them on to the stack until all of them are processed. -
We simulate that we are getting a bunch of recipe IDs from a server.
Based on that, we select a recipe through the ID and then get that recipe from a server.
* We are going to use the setTimeout function to simulate getting the data from a server.
* This will generate a callback hell, where there are many callback functions inside one another, forming a triangle. - Promises are used to prevent the callback hell, seeing on the Recipes example, from happening.
a) It's an Object that keeps track about whether a certain event has happened already or not, like a timer finishing or some data coming back from an AJAX call.
b) Determines what happens after the event has happened, with then and catch.
c) Implements the concept of a future value that we're expecting. Like we are gonna handle a value in the future that is yet to be obtained. - Promises take two arguments, as in: new Promise(resolve, reject), which are the callback function's resolve and reject, these are being used to inform the promise if the event it is handling was successful or not.
- States
So, a Promise can be either FULFILLED or REJECTED.
Fulfilled is consumed with then and rejected is consumed with catch. - Example:
Promises and Async/Await
The async/await function returns a promise. Every async event returns one. - AJAX - Asynchronous JavaScript And XML
Basicly it allows us to asynchronously communicate with remote servers.
So we can get data from the servers without loading the page. - API - Application Programming Interface
a) Piece of software that can be used by another piece of software in order to allow applications to talk to each other.
b) The API is not the server itself, but it's like a part of the server, like an application that receives requests and sends back responses.
c) API key: it's like a password that is given each user, it's like a unique ID that each user can use in order to make requests and so that that API can track how many requests you make per day.
Example: in the Forkify project we have a free plan, where we can make 50 requests to the API in a day, so search for recipes 50 times.
Remember that web API is one of the parts that are available to us in the browser but is not part of the JS language itself.
Your own APIs
You could build you own API that can receive requests from your front end app in JS and send back the results.
- This would be your own API, hosted on your server.
External APIs, third party APIs
Let's say we need to get the current weather information, which is not in our database.
For that, we could use an external API.
- Fetch
Fetch - buscar, trazer.
Fetch is a modern web API.
With Fetch we can do AJAX in a very simple way, so we can do asynchronous network requests across the internet to fetch data from other servers, or even from our own server.
This was also done through the XML HttpRequest interface, it has better web support than fetch for being around for longer.
Syntax: fetch(URL where API is located)
Fetch returns a promise, so we have to consume it with then or catch.
- JSON
Text-based data format similar to JS objects, however, JSON is a single string and not an entire object inside the JS engine.
It would be a text, string, that we receive and then convert it to a JS object.
- CORS - Cross Origin Resource Sharing
There's a same origin policy in JS, which basically prevents us from making AJAX requests from different domains.
Now, to allow developers to make requests to different domains, CORS was created.
This is to be implemented into the API.
If the API doesn't have CORS implemented, we can proxy or channel the request through their own server, like doing the AJAX requests on our own server where the same origin policy doesn't exist and then send the data to the browser.
crossorigin.me does this for you. - Try and Catch statments
It tries to execute the code and if there's an error, it will execute the catch.
try {
// executes this code.
} catch(error) {
// if there's an error, do this.
}
AJAX and APIs