Creating A Promise In JavaScript

In JavaScript, a promise is an object that symbolises the eventual success (or failure) of an asynchronous operation and the value that results from it. In JavaScript, asynchronous operations like network requests, file reading, and setTimeout are handled using promises.

There are three states for promises:

  • Pending : A state that was neither fulfilled nor rejected in the beginning.
  • Fulfilled : Indicating that the process was successful.
  • Rejected : Indicating that the process was unsuccessful.

There are two major ways to make promises:

  • .then() : When the promise is fulfilled, this method is invoked, and it produces a new promise that includes the outcome of the original promise.
  • .catch() : When the promise is denied, this method is invoked, and it produces a new promise along with the rejection’s justification.

Here’s an example of a simple promise:

let promise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("done!"), 1000);
});

promise.then(result => console.log(result));

In this case, the promise is fulfilled after one second with the value “done!” The outcome is recorded to the console by the.then() method.

You can run a number of asynchronous activities in succession by chaining promises together.

let promise1 = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("done!"), 1000);
});

let promise2 = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("again!"), 2000);
});

promise1
  .then(result => console.log(result))
  .then(() => promise2)
  .then(result2 => console.log(result2));

In this example, promise1 is fulfilled first, and then promise2 is completed and logs “again” after waiting one second.

The introduction of Promise in ECMAScript2015(ES6) makes it simple for Javascript to conduct async tasks.

There are numerous utility methods that may manage and manipulate multiple promises simultaneously, including Promise.all(), Promise.race(), Promise.resolve(), and Promise.reject().

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories