
This course includes our updated coding exercises so you can practice your skills as you learn.
See a demo
Hello and Welcome, to a very practical Asynchronous Javascript course.
This course will be divided in very short, digestible and practical lessons which will contain an example and a quiz at the end of each.
We will learn about Asynchronous code, Callback functions, Then/Catch for Promises (Error handling), the Async-Await notation, and Promise Chaining.
At the end of the course we will build a small weather widget with real data.
What is synchronous code?
What is asynchronous code?
What are the differences?
In this lesson we will explore the concept of Asynchronous Code, and where is it needed.
Let's first setup our environment. With it you'll be able to reproduce and expand on the code I will write throughout the course.
I recommend you install NPM (https://npmjs.com, to install: https://www.npmjs.com/get-npm) which is a NodeJS Package Manager. All the Frontend developers in the world use such a library (there's also Yarn and others, but they all do the same.) NPM is going to simplify your life if you start building bigger apps.
If you don't want to install NPM, i will also show you how to setup your local environment.
=====
I will be using Visual Studio Code. It's the best free editor out there and I strongly recommend it: https://visualstudio.microsoft.com
We will learn about Callback Functions. When we call a function we pass values as arguments, like in `var result = multiply(a, b)`. But we could also pass a function as a parameter. The way the Mozilla Development Network describes it:
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
We will touch the three syntaxes to declare a function:
`function sayHello(name) { ... }`
`const sayHello = function(name) { ... }`
`const sayHello = (name) => { ... }`
Armed with this, we can ask ourselves: What is an Immediately Invoked Function? Sometimes it's easier to understand code if the functions are anonymous.
Let's put to practice what we have just learnt and do some maths! 3rd Grade Maths, so no worries.
We will create a function `double(a)` which will print the result of a*2 into our custom logger.
As a quiz you'll create a similar function called `multiply`.
What is a JavaScript Promise?
When do we need it?
How do we use it?
We will learn the basic definition of Promise, look back at our example in Lesson 2 (Synchronous Code) and learn how we can solve the problem we faced.
We will perform a request to RandomUser Api (a service we will use throughout the course) and learn the concept (more details in future lessons!) of a rejected promise: it throws an error!
We will perform a request to the Wikipedia Summary API, which allows us to get extracts of articles. (https://en.wikipedia.org/api/rest_v1/page/summary/Udemy). These requests/responses are in the JSON format.
As a Quiz, you should do the same we did but with the Reverse IP API.
Now that we know about Asynchronous Code and Promises, we will learn the other syntax: Async / Await. This syntax is a new syntax from 2016/2017 which allows us to write Asynchronous code but keeping the clean and clear syntax that normal, synchronous code provides.
Instead of:
axios.get(...).then(result) => {
console.log(...)
});
We can just do:
const result = await axios.get(...);
console.log(result);
Let's make a similar (but a bit more advanced) example fetching the Wikipedia Article like we saw on Lecture 8. This time we can pass a parameter to the function, and we will re-write the code using the async/await syntax we've just learnt.
Same as on Lecture 8, I will leave as a Quiz to do the same for the Reverse IP request - You need to write it in the async/await syntax as well.
Promises don't always resolve, sometimes they are rejected. This can happen for many many different reasons:
Website does not exist
Uri does not exist (404)
Client loses connection
Server encounters an error (500)
Server returns an error (401 Unauthorized, 403 Forbidden, 400 bad request ...)
Our code inside of ".then()" fails
...
All of this cases can be solved by adding a ".catch()" block to our object.
In order to have a clear overview of what can happen, and how it can happen, I created this diagram for you - Now i can explain much better all the possible ramifications.
Same as we did in Lecture 11, we will learn the same concept but in this case with the async/await syntax.
We will also answer the very important question:
Does try/catch also work with the .then() syntax in Asynchronous code? NO.
Whenever we enter the .catch() block, are we able to determine the type of error? The answer is sometimes, and we will see an example where we can distinguish it.
Your job in this Quiz is to implement error handling for the Wikipedia Article function we saw on Lecture 8.
Sometimes, when we want to request many resources/data at once, we can speed up the loading time by performing the requests in Parallel. This can be done using Promise.all().
In this chapter we will see a theoretical example when this can be used.
We will also learn the `destructor` syntax of Javascript, which will prove to be very useful in keeping our code tidy.
We will learn how to call many requests in parallel using the async/await syntax.
There are two ways:
Defining the promises before they are awaited
const usersPromise = getUsers();
const postsPromise = getPosts();
const users = await usersPromise;
const posts = await postsPromise;
Using the Promise.all():
const [users, posts] = await Promise.all(getUsers(), getPosts());
Even though the first syntax might look (and probably is) more complicated, i wanted to show it to you anyway because you get a better understanding of how things are working under the hood. Besides, explaining `await Promise.all()` wouldn't be worthy of a whole lesson.
But just so you know, you can use both syntaxes.
In this short Example Lesson we are going to implement Promise.all() for the Wikipedia article and call two articles at the same time.
The total execution time is less than 0.25 seconds!
Similarly to the previous example in Lesson 18, we are going to fetch a Wikipedia article and a random user at the same time and display them.
We are going to briefly touch on two other methods of the Promise object:
Promise.race([a, b, ...])
Promise.allSettled([a, b, ...])
These are so obscure that i have never had to use them in my whole career. I have even asked colleagues and it doesn't seem to be very popular. This course, however, wouldn't be complete without at least mentioning them.
Chaining is exactly what it sounds like: Attaching a function to a function to a function... in our case these are both .then() and .catch() functions.
By calling a promise and successfully attaching several .then() callbacks we can manipulate the object in a very clear and syntactically pleasing way:
(.....).then(doSomething).then(doSomethingElse).catch(...).then(...)
We will see an example of an application where returning a value and passing it to the next `.then()` is easier to read and write than storing intermediate variables in the same blocks. Watch the lesson to understand what I mean by this
Putting into practise all we've learnt about chaining promises, we'll chain two promises and get the Wikipedia article for our country based on our IP.
Throughout the whole Course we have only used Asynchronous requests with the `GET` method, hence the `axios.get(...)`.
There are other methods with its own application/convention/use cases, and i'm going to briefly explain what each of those is.
We've finished the theory, the examples and the quizes! Now it's time to build something with what we've learnt.
We are going to build a weather widget, using things we've learnt such as:
Performing asynchronous requests (obviously)
Performing a request and using its result to perform another request (requests in series)
Chain the first request to the other ones
Perform requests in parallel
Manipulate objects in a .then() block and return them
Once we've done this, and once we return the data in the correct format, our Weather Widget will come to live and will display real weather data and weekly forecast.
Welcome to my Udemy course on Asynhcronous JavaScript!
On this very practical course we will focus on results.
How to request data from a server
How to manipulate these data
When to request data in parallel
How to request data which depends on a previous response
How to handle errors properly
Use the async/await syntax
And finally, armed with all these tools, we'll build a weather widget which fetches real data and shows the forecast for the week based on your location.
===========
The course is divided in five big sections:
Callback Functions - We will learn what a callback function is and when it is used. We will also explain the concept of Immediately Invoked Function Expressions.
Promises - What is a Promise, how does JavaScript wait for its response...
Error Handling - Promises can fail, and for this reason we must know how to catch possible errors and handle them properly.
Promise Object and parallel requests - We can speed up our request 40% or more by performing certain requests in parallel. We will wait until we have received both "responses" before continuing with our code.
Promise Chaining - Handle a complex chain of parallel and series requests in one single object - for better readability and code practices.
All of these major points we will learn both using the Promise syntax ( axios.get(...).then(response)...) and the async/await syntax (const response = await axios.get(...))
And finally
We will build a Weather Widget using all the knowledge from this course.