DEV Community

Cover image for Promises & Async/Await
Karthick (k)
Karthick (k)

Posted on

Promises & Async/Await

Why JavaScript promises

The following example defines a function getUsers() that returns a list of user objects:

function getUsers() {
  return [
    { username: 'john', email: 'john@test.com' },
    { username: 'jane', email: 'jane@test.com' },
  ];
}
Enter fullscreen mode Exit fullscreen mode

Understanding JavaScript Promises

By definition, a promise is an object that encapsulates the result of an asynchronous operation.

A promise object has a state that can be one of the following:

  • Pending

  • Fulfilled with a value

  • Rejected for a reason

In the beginning, the state of a promise is pending, indicating that the asynchronous operation is in progress. Depending on the result of the asynchronous operation, the state changes to either fulfilled or rejected.

The fulfilled state indicates that the asynchronous operation was completed successfully:

Creating a promise

To create a promise object, you use the Promise() constructor:

const promise = new Promise((resolve, reject) => {
  // contain an operation
  // ...

  // return the state
  if (success) {
    resolve(value);
  } else {
    reject(error);
  }
});
Enter fullscreen mode Exit fullscreen mode

Note that the callback functions passed into the executor are resolved and rejected by convention only.

Consuming a Promise: then, catch, finally

1) The then() method:

To get the value of a promise when it’s fulfilled, you call the then() method of the promise object. The following shows the syntax of the then() method:

promise.then(onFulfilled,onRejected);
Enter fullscreen mode Exit fullscreen mode

2) The catch() method

If you want to get the error only when the state of the promise is rejected, you can use the catch() method of the Promise object:

promise.catch(onRejected);
Enter fullscreen mode Exit fullscreen mode

Summary

  • Use then() method to schedule a callback to be executed when the promise is fulfilled, and catch() method to schedule a callback to be invoked when the promise is rejected.

  • Place the code that you want to execute in the finally() method, whether the promise is fulfilled or rejected.

References:

I have written about this article and I am learning about this topic's future. I will updated more
I've learned a lot from this article about JavaScript promises, and I'm planning to update my notes as I continue my studies on the topic. I'm excited to explore how promises can be used in asynchronous programming and their impact on code structure. If I come across more information, I’ll make sure to revise and add to my understanding!

https://www.javascripttutorial.net/es6/javascript-promises/

Top comments (1)

Collapse
 
raja_b_0c9d242e2c26cf063b profile image
Raja B

Mr.karthik

why this reson using for promise understand explian???