My FeedDiscussionsHeadless CMS
New
Sign in
Log inSign up
Learn more about Hashnode Headless CMSHashnode Headless CMS
Collaborate seamlessly with Hashnode Headless CMS for Enterprise.
Upgrade ✨Learn more
Promises in JavaScript

Promises in JavaScript

Anjali Chauhan
·Jul 22, 2022·

3 min read

The Promise object represents the eventual completion (or failure) of an asynchronous operation and its resulting value. ~ MDN docs

So This statement is less helpful if you do not understand what is Asynchronous

image.png

  • The normal code is Synchronous in nature.

  • One statement is executed and there is a guarantee that the next statement will execute immediately after this.

  • JavaScript Threading Model ensures that JavaScript code runs in a single timeline.

  • Asynchronous Code does not guarantee to execute in a single unbroken timeline.

  • In fact, you should assume that You have no idea when asynchronous operations will complete.

  • You cannot assume that execution will happen the way you write the code statements. It may happen that lines of code fail altogether.

EXAMPLES OF ASYNCHRONOUS CODE

image.png

WHAT IS THE BEST TO HANDLE ASYNCHRONOUS CODE? 🤔

ANSWER is Promises 💘

CALLBACK VS THEN ⚔️

Callbacks are the default JavaScript Technique for Asynchronous Code.

Pass the Function in another Function and then call the callback function at some later time when some conditions have been met.

image.png

  • What if an Error occurs at position1 then what should you execute callback at position2. Then what value should it receive and If not then what should happen (in the image above)? ☹️
  • What if there's JavaScript Error undefined is not a Function Should it be handled differently than a network call?
  • Another Situation is when Callback at Position2 is also an Asynchronous Function 👾

PYRAMID OF DOOM 🪦

Screenshot 2022-07-22 210347.png

The Dreadful situation is when there is nested callback within callbacks, within callbacks.

  • Looks ugly
  • Hard to write
  • Frustrating to Debug

BEAUTY OF .Then 🌼

image.png

This code is written with Promises and it looks nicer.

PROMISES TERMINOLOGY

image.png

Promises are a bit like event listeners except:

  1. A promise can only succeed or fail once. It cannot succeed or fail twice, neither can it switch from success to failure or vice versa.
  2. If a promise has succeeded or failed and you later add a success/failure callback, the correct callback will be called, even though the event took place earlier.

4 STAGES OF PROMISES

  • fulfilled - The action relating to the promise succeeded
  • rejected - The action relating to the promise failed
  • pending - Hasn't fulfilled or rejected yet
  • settled - Has fulfilled or rejected

CREATING A PROMISE

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 one argument, a callback with two parameters, resolve and reject.
  • Do something within the callback, async, then call resolve if everything worked, otherwise call reject.

  • Like throw in plain old JavaScript, it's customary, but not required, to reject with an Error object. The benefit of Error objects is they capture a stack trace, making debugging tools more helpful.

HOW YOU USE THAT PROMISE

promise.then(function(result) {
  console.log(result); // "Stuff worked!"
}, function(err) {
  console.log(err); // Error: "It broke"
});

then() takes two arguments, a callback for a success case, and another for the failure case. Both are optional, so you can add a callback for the success or failure case only.

then() isn't the end of the story, you can chain thens together to transform values or run additional async actions one after another.