A simple guide to using promises in JavaScript

A simple guide to using promises in JavaScript

A promise in JavaScript is like the real-life scenario of making a promise, either you keep your promise or you break it. But with JavaScript, it gets either resolved or rejected.

Photo by Valentin Antonucci on Unsplash

Let’s look at an actual world scenario. For example, you have a schedule to read a book every day, meaning you have promised to dedicate a few hours out of your day to reading a book.

Promise Example

A promise takes two callbacks, that is resolve and reject. The above example, it shows they fulfilled the promise to read a book that day. Therefore, our Promise will be resolved and hence return to “ Read A Book Today” as its response.

If they failed to keep their promise then readABookToday would be set to false. Therefore, our Promise will be rejected and hence return to “Couldn’t Read A Book Today”.

The moment promiseToReadABookEveryday gets executed, the then function will be triggered if the promise gets resolved. The catch function will be triggered if the Promise gets rejected.

The result is the value returned in the resolve() or reject() depending on the result of the promiseToReadABookEveryday*,* whether it was resolved or rejected.

Further Read, MDN Promises Article.