JavaScript Promises

JavaScript Promises

JavaScript's Promise is similar to a real-life promise. Like when you make a promise to someone; for instance, I promise to return your book by evening. Two outcomes can happen - I can either return the book or I won't. If I return it, I have fulfilled my Promise, which means the Promise is resolved; if I don't, it means I failed to keep it, or the Promise is rejected!

Let's take the example of a promise variable equal to a new Promise object. We'll pass a function into it which takes two parameters (resolve and reject). Then, we'll define our function using an arrow function. If you're unfamiliar with arrow functions, they're a new feature of ES6. You should check them out in more detail in the next tutorial. Now, let's examine what a real promise looks like. I'll take the previous example, with my Promise to return the book by evening. Let's see how we interact with whatever result we get.

With p.then(), whatever is inside resolve will go into then. Say I return the book by evening, then you'll do something else like read the book, but only if I give it to you; let's see the syntax… It will take a single parameter as we give a single parameter result. Whatever has been returned will be logged here!

But what if I don't return the book? That will go into the catch block. Let's observe its syntax.. Catch will be called in syntax if I don't fulfill the Promise. Let's run this and see the result.. In the video explanation, if the Promise is fulfilled (resolved) it will go in the then block and if the Promise is not fulfilled, it will be rejected and go into the catch block!

Why do we use Promise?

We use a Promise when we have to wait for a response. Like I had to return the book in the evening, I needed to promise that I'd return the book by evening! Similarly, if I have to download an image from the server on the web, I'll use a promise to ensure the remaining content loads after the image downloads. It'll send an error into the catch block if it doesn't load.