Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

What is promise in JavaScript

What is a Promise?

Imagine you are in a restaurant and you have just placed your order. The waiter doesn’t make you wait at the counter while your food is being prepared. Instead, they give you a buzzer and promise that when your food is ready, the buzzer will alert you. In the meantime, you are free to do other things, like chatting with friends or sipping your drink. This is how Promises in JavaScript work!

A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. Essentially, it's a returned object to which you attach callbacks, instead of passing callbacks into a function.

In JavaScript, a lot of operations are asynchronous, like getting data from a server or reading a file from disk. These operations don't complete immediately, and JavaScript doesn't wait for them to finish. Instead, you get a Promise that the operation will complete in the future.

Structure of a Promise

A JavaScript Promise object contains two callbacks: resolve and reject. The Promise constructor takes one argument, a callback with two parameters, resolve and reject.

let myFirstPromise = new Promise((resolve, reject) => {
  // do something asynchronous which eventually calls either:
  //
  //   resolve(someValue); // fulfilled
  // or
  //   reject("failure reason"); // rejected
});

resolve is called when the Promise is to be fulfilled, and reject is called when the Promise is to be rejected. In our restaurant example, resolve is when your food is ready and the buzzer goes off. reject is when there's a problem with your order and the waiter comes back to tell you.

How to Use a Promise?

When a Promise is pending, you can attach callbacks to it that will be invoked when the Promise is fulfilled or rejected. This is done using the .then() and .catch() methods.

myFirstPromise.then((value) => {
  // on fulfillment (resolve)
  console.log('My order is ready!', value);
}).catch((reason) => {
  // on rejection (reject)
  console.log('There was a problem with my order.', reason);
});

The .then method takes two arguments: a callback for a success case (resolve) and another for the failure case (reject). The .catch is just a shorthand for .then(null, errorCallback).

Handling Multiple Promises

In JavaScript, you can handle multiple Promises at once using Promise.all(). This function returns a new Promise that fulfills when all of the passed Promises have fulfilled or when any of the passed Promises are rejected.

let promise1 = Promise.resolve(3);
let promise2 = 42;
let promise3 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'foo');
});

Promise.all([promise1, promise2, promise3]).then((values) => {
  console.log(values); // expected output: Array [3, 42, "foo"]
});

In the above code, Promise.all is given three promises, and it returns a new Promise that fulfills when all three promises have been resolved. The value of this Promise will be an array containing the resolved values of each Promise.

Conclusion

Just like the waiter's promise to alert you when your food is ready, Promises in JavaScript tell you when an asynchronous operation has finished. They help you manage asynchronous code, making it easier to reason about and maintain.

Promises are not just a feature of the language, but a paradigm shift. They change how you approach problem-solving in JavaScript, making your application more efficient and robust. So the next time you find yourself waiting for an asynchronous operation to complete, remember the waiter and consider using a Promise.