Hi everyone, today we will be looking into what promises are, .then()
, .catch()
methods and why async
await
is a better option.
When we are dealing with simple types in javascript such as strings and numbers, our code executes sequentially.
We can just declare strings and numbers and can print them right away. But in the real-world scenario, we might fetch some data from a database or make some API call over the internet. Task's like these take some time to finish and might not return the results straight away, they would rather return a Promise
.
Promise: The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value.
--developer.mozilla.org
This might sound a bit confusing, so let's look at an example. Imagine you are at a restaurant and you asked the waiter to bring you a pizza, the waiter promises to come back with your pizza. However you can't eat your pizza at that point, you have to wait until he/she returns with your pizza and the promise is fulfilled. This is the same sort of concept in JavaScript as well.
You are just requesting some information from a remote API and you are immediately given a Promise
that your task will either complete or fail. It's not until sometime later the promise is resolved or rejected that you can use a result of that promise.
Now let's write a JavaScript program that uses "Bored API" (Bored API just return random suggestion of things that you can do along with the number of participants required).
But will this program work?
The answer is no. Why?
This won't work because the API when called gives us a Promise
that is not resolved immediately. So our program doesn't know what .data.activity
is when we try to print it.
So is there any way we can just wait for a Promise
to resolve and then continue executing our code? Yes, there are multiple ways that JavaScript gives us to wait until the task is finished and use the result or catch any errors that occurred in the process.
.then().catch()
The first way is by using a couple of special methods on the promise object. The first one is called then()
. then()
is called when the task completes, as a parameter it receives the result of the task. The second one is called catch()
. catch()
is called when the task fails, as a parameter it receives the error that occurred while processing the task.
Here as you can see we are using axios library for the get
request and we are using .then()
function that will return some "success" message. We are also using the .catch()
function that will return some error if something goes wrong.
In our case, the API is working and there are no errors. Now to simulate an error occurring in our request, let's replace the URL with HTTP status API(very useful for testing different status codes). So our program will look something like this
As you can see our error is neatly caught by the .catch()
method.
Something to note is that the code written after this will be executed immediately. So if we console log here at the bottom, we expect it to be written after our request returns.
But in reality, it gets printed out first.
This is because only the code written inside .then()
and .catch()
methods are executed after the request returns.
So as you can see the code that is returned is not really in any particular order and if you had a lot of complicated code it might get a little bit confusing. So what we need is a way to get the results of our promises sequentially just like we were printing strings and numbers.
Async and Await
So this is when the await
keyword comes in.
Await: 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.
--developer.mozilla.org
And an await
does exactly what it says, waits for the promise to be fulfilled and then only executes the code after it. But you can only use it inside an async
function.
Here it will only execute the console.log when the Promise
resolves.
But since the await
keyword allows us to move this block of code back into the main flow of our app, we don't have access to the .catch()
method.
Since the code is executing sequentially, we can just use a normal try{}
-catch(){}
method. Let's simulate an error by using HTTP status API and see whether it works or not.
And It does.