Promise? ๐Ÿคž

Promise? ๐Ÿคž

ยท

3 min read

Introduction

Javascript is a synchronous language, and If we want to introduce an async task in our program, the promise is one of the ways to do it. A promise is an object which indicates the future completion of the task. It can be in one of three possible states,

  • pending: initial state, neither fulfilled nor rejected.
  • fulfilled: meaning that the operation was completed successfully.
  • rejected: meaning that the operation failed.

Example of Promise

Lets make an promise (In more ways than one ๐Ÿ‘€),

const p1 = new Promise((resolve,reject)=>{
  const flag = 10
  if(flag){
    resolve("Promise Resolved")
  }
  else{
    reject("Not Fulfilled")
  }
})


p1.then(res=>console.log(res)).catch(err=>console.log(err))

In the above example, promise p1 is declared, and two arguments were passed. Based on the flag variable value, the promise is resolved or rejected. ( for this case, flag = 10, so the if statement was true; hence promise got resolved and gave us an output of Promise Resolved)

Why promise?

Introducing async abilities in javascript is nothing new. We can use callback and other Web APIs for that, so why do we need promise? Well, for the starters, Promises help in reducing callback hell. Now, what's that? Before promises, what usually used to happen was use callback for introducing async features in a js program. one callback use to depend on second and second on third, thus making a whole mess in writing and debugging the code. Promises were introduced to resolve this problem.

Different Promise methods

Handling multiple promises is a little tough alone, that's why javascript provides promise methods. These are some of the methods we are going to discuss today, Promise.all(), Promise.race() & Promise.any().

.all method

Promise.all() method takes a list of promises as inputs and returns the result of those promises in an array.

The only problem with this method is, that if any of the promises from the list get rejected, it goes to the catch() block.

const promise1 = Promise.resolve(3);
const promise2 = 42;
const 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"]

The above code-block from MDN shows three promises were passed in promise.all() and the output was an array of results from those promises.

.race() method

This is another widely used promise method. This one takes multiple promises as a last and returns which one of the resolves or gets rejected first.

const promise1 = new Promise((resolve, reject) => {
  setTimeout(resolve, 500, 'one');
});

const promise2 = new Promise((resolve, reject) => {
  setTimeout(resolve, 100, 'two');
});

Promise.race([promise1, promise2]).then((value) => {
  console.log(value);
  // Both resolve, but promise2 is faster
});
// expected output: "two"

The above code-block from MDN shows the program only outputs two as promise2 is faster than promise1.

.any() method

Promise.any() like others takes a list of promises and outputs the promise which first gets resolved. If none of them gets resolved then the returned promise is rejected with an error. Lets look at the code,

const promise1 = Promise.reject(0);
const promise2 = new Promise((resolve) => setTimeout(resolve, 100, 'quick'));
const promise3 = new Promise((resolve) => setTimeout(resolve, 500, 'slow'));

const promises = [promise1, promise2, promise3];

Promise.any(promises).then((value) => console.log(value));

// expected output: "quick"

As you can see, the output of the above program is quick because pormise2 got resolved first.

Conclusion

If you made till here, you are awesome. The main goal of the blog was to learn about promise methods myself. I got asked this question in one of the mock interviews and I could not answer for one of the methods correctly. So thought of writing a blog and practicing the concept.

If you have any suggestion for this blog or any other project I am working on, Feel free to do so by texting on twitter.

ย