HomeAbout MeContact

Javascript Promise Overview

By Spencer Barriball
Published in Coding
December 19, 2021
2 min read
Javascript Promise Overview

Javascript promises are what they say on the tin: Let’s say I promise if you study hard and understand Javascript to a decent level I will give you a job working for a software house. After a few months you would have either learnt enough to get that great job or you will continue learning in order for the promise to be fulfilled.

Promise syntax

let promise = new Promise(function(resolve, reject) {
 // code to be executed (the executor)
});

Inside a new Promise, there is a function that immediately launches the created promise. It doesn’t know the result now, it only promises that you’ll get a value later on. The main benefit of any promise is that the program continues running while the promised value is being retrieved. As soon as the executed function has finished, you’ll get the result and the contract will be fulfilled.

This means if you were viewing a site that used an API to grab things (let’s say an image icon) instead of waiting for the image / API to resolve we can view the page while the promise is being executed. Neat eh?

There are two arguments inside the executor: resolve and reject. These pre-defined functions are called depending on whether the promise was successful or failed: • resolve(value) in case of success. • reject(error) in case of failure.

Promise states

A promise is an object that has a state property. At any time can be in one of these states: • pending: still running. • fulfilled: resolve function is called. • rejected: eject function is called.

Examples:

function myDisplayer(some) {
  document.getElementById("demo").innerHTML = some;
}

let myPromise = new Promise(function(myResolve, myReject) { 
  let x = 0;

// The producing code (this may take some time)

  if (x == 0) {
    myResolve("OK");
  } else {
    myReject("Error");
  }
});

myPromise.then(
  function(value) {myDisplayer(value);},
  function(error) {myDisplayer(error);}
);

That’s the basics of promises now when it resolves or rejects there are three promise methods that we use: .then.catch, and .finally.

.then

.then method is used to handle good or bad promise results. Let’s look at an example: say, we’re working on a program that helps busy people keep track of their dentist appointment dates. We create a promise to let the user know if they missed their appointment based on the current date. If the event hasn’t taken place yet, we resolve the “Don’t forget your dental appointment” value; otherwise, we reject with the error text “You have missed your appointment!”.

const examDate = new Date(2021, 12, 19);
const promise = new Promise(function(resolve, reject) {
  const currentDate = new Date();
  if (currentDate < examDate) {
    resolve("Don’t forget your dental appointment");
  } else {
    reject("You have missed your appointment!");
  }
});

It completes then we do this:

promise.then(
  function successStatus(response) {
    console.log(response);
    return response;
    },
  function failStatus(error) {
    console.log(error);
    return error;
  }
);

So, the .then method is used to work the promised result and launch certain actions based on it. Both arguments of .then are optional.

.catch

Let’s say we need to handle catching errors as well, take a look below:

promise
  .then(function successStatus(response) {
    console.log(response);
    return response;
  })
  .catch(function failStatus(error) {
    console.log(error);
    return error;
  })

.finally

The method .finally is used when we want to invoke a function after the promise was settled, regardless of the promise state. This is how that works:

promise
  .then(function successStatus(response) {
        console.log(response);
        return response;
  })
  .catch(function failStatus(error) {
    console.log(error);
    return error;
  })
 .finally(function finalMessage() {    
    console.log(“This always gets printed at the end”);
  });

The text “This always gets printed at the end” will be shown after the promise has been settled. The user will see it no matter if the promise was resolved or rejected. It’s useful when you have some required actions that don’t depend on the result of the promise.

Promise chaining

Suppose you have some scripts depending on other scripts, and you need to load them sequentially.

loadStuff(“https://website-one.com/first”)
  .then(function() {
    return loadData("https://website-one.com/second”);
  })
  .then(function(id) {
    return loadData(`https://website-one.com/first_${id}`);
  })
  .catch(function(error) {
    console.log(“Hey, sorry but there was an error”, error)
  });

Do keep in mind that to make the code asynchronous, you should return the promise at each step.


Tags

jsjavascriptcodingtutorial
Previous Article
So you want a Shiba Inu?
Spencer Barriball

Spencer Barriball

Full Stack Web Dev

Topics

Random
Coding
Career
Pets
React

Related Posts

Some handy links for basic website development
December 26, 2021
2 min
© 2023, All Rights Reserved.

Quick Links

Advertise with usAbout UsContact Us

Social Media