JavaScript: Promises explained with simple real life analogies

Talking about promises in layman terms

Shruti Kapoor
codeburst

--

A promise being initiated. Photo by Ben White on Unsplash

Promise: In Layman terms

Think of it as a conversation between two people:

Alex: Hey Mr. Promise! Can you run to the store down the street and get me itemA for this dish we are cooking tonight?

Mr. Promise: Sure thing!

Alex: While you are doing that, I will prepare itemB(asynchronous operation). But make sure you let me know whether you could find itemA (promise return value).

Mr. Promise: What if you are not at home when I am back?

Alex: In that case, send me a text message saying you are back and have the item for me (success callback). If you don’t find it, call me immediately (failure callback).

Mr. Promise: Sounds good! See you in a bit.

So simply speaking, promiseobject is data returned by asynchronous function. It can be a resolveif the function returned successfully or a rejectif function returned an error.

Promise: The definition

A Promise is an object representing the eventual completion or failure of an asynchronous operation. Essentially, a promise is a returned object you attach callbacks to, instead of passing callbacks into a function.

Promise: In JavaScript

Let us first talk about JavaScript and its concurrency. JavaScript is single-threaded. Everything happens in the sequence it is written, line-by-line. But, asynchronous operations occur in the order they complete.

What do you think is logged in the console in the following example?

console.log("1");
setTimeout(function(){console.log("2");},3000);
console.log("3");
setTimeout(function(){console.log("4");},1000);

The output will be 1 3 4 2 . You may wonder why 4 is logged before 2. The reason for that is that even though line 2started executing before line 4 , it did not start executing for 3000ms and hence 4 is logged before 2 .

In a typical web-app, you could be doing multiple asynchronous operations, such as fetching images, getting data from JSON endpoint, talking to an API, etc.

Now, let’s look at how you create a promise in JavaScript:

var promise = new Promise(function(resolve, reject) {
// do a thing, possibly async, then…

if (/* everything turned out fine */) {
resolve("Stuff worked!");
}
else {
reject(Error("It broke"));
}
});

The promise constructor takes in one argument: a callback function with two parameters — resolve and reject. This promise can then be used like this:

promise.then(function(result) {
console.log("Promise worked");
}, function(err) {
console.log("Something broke");
});

If promise was successful, a resolve will happen and the console will log Promise worked, otherwiseSomething broke. That state between resolve and reject where a response hasn’t been received is pending state. In short, there are 3 states to a promise:

  1. pending: awaiting promise response
  2. resolve : promise has successfully returned
  3. reject: failure occurred
Promise returned successfully. Photo by Scott Webb from Pexels

Promise: Example

To fully understand the concept of promises, lets create an app which loads an image. If image is loaded, we will display the image, or else log an error.

First, lets create a promise using XMLHttpRequest(XHR).

Now, when the image is successfully loaded, promise will resolve with the response from XHR. Let’s go ahead and use this promise by calling the loadImage function.

And that’s it! Not too bad, eh?

Now you go ahead and make some promises! Go on.

Further reading

Here are some articles that I found really helpful while learning promises:

  1. Mozilla MDN
  2. Google developers
  3. Concurrency model

If this post was helpful, sign up for my JavaScript newsletter.

--

--