Introduction to JavaScript Promises

Introduction to JavaScript Promises

JavaScript Promises are just like promises in real life. Promises in JS promise us to make the result. In this way, we can handle the asynchronous operations in JS. Now let’s understand Promises with examples.

javascript promises

JavaScript Code Runner on: promise

Here we are going to write a simple js code where we will be using the setTimeout function.

var info = " this is a car ";
setTimeout(function () {
  info = "this is not a car";
}, 2000);
console.log(info);

We will get ” this is a car” as the output because the function will run after 2sec. But we want to get the value of info from the function. Therefore we have to make the code asynchronous. In that case, we will be using promises to make the code asynchronous.

function getAfter() {
  console.log("this is a car");
}
 
let info = new Promise(function (resolve, reject) {
  setTimeout(() => resolve("this is not a car"), 1000);
});
info.then(
  (result) => {
    console.log(result);
    getAfter();
  },
  (error) => {
    console.log(error);
  }
);
// Output:
sorry, this is not a car
this is a car

Here we will get the desired output. The whole code will wait till the setTimeout function runs. This is the power of promises.

The basic structure of promises

let info = new Promise(function (resolve, reject) {
  setTimeout(() => resolve("value"), 1000);
});
info.then(
  (result) => {
    console.log(result);
  },
  (error) => {
    console.log(error);
  }
);

This is a basic structure of promises. Here we have a function which is having two parameters one is “resolve” and another is “reject”. If this function resolves the result it will run the result otherwise it will show err. It makes the function asynchronous.

Related: How to send Email using NodeJS

Here info.then waits for the result of the promises function. Here info.then executes after the setTimeout function completes its task. If there is an error in that function, it will directly move to error.

Advantages of Promises

  • Promises reduced coupling.
  • It’s good for handling asynchronous operations.
  • It has improved readability.
  • It is having a better defined and organized control flow of asynchronous logic.
  • Compatible (opens in a new tab) with the Majority of the browsers

Summing Up

This was a basic snippet-based idea to help you understand the logic behind Javascript Promises. Soon I’ll compose some tutorials on ‘Async await’, so stay tuned for that.

IndGeek provides solutions in the software field, and is a hub for ultimate Tech Knowledge.