본문으로 건너뛰기

Promise

Promise

A Promise is an object representing the result of an asynchronous operation in JavaScript.

What does asynchronous mean here?


Synchronous & Asynchronous Communication

Communication over a network is broadly divided into Synchronous and Asynchronous communication.

Synchronous communication is a method where tasks are processed one by one in order, and the next task is put on hold until the previous one is finished. Asynchronous communication is a method where multiple tasks are carried out simultaneously, and the results of specific tasks are handled as they are completed.


Promise

A Promise is an object in JavaScript that represents the result of an asynchronous operation.

A promise indicates the value of an asynchronous operation after it has finished or the reason why it failed.

Promises are mainly used for handling asynchronous tasks such as communication with servers and events.


Example

Promise Example
let myPromise = new Promise((resolve, reject) => {
let isDone = true;

if (isDone) {
resolve('Work completed');
} else {
reject('Work failed');
}
});

myPromise
.then((result) => {
console.log(result); // Work completed
})
.catch((error) => {
console.log(error); // Work failed
});

In the example above, myPromise creates a Promise object, which calls resolve() if the task is successfully completed, and reject() if it fails.


Characteristics

  1. States: A promise has three states.
  • Pending: The asynchronous operation has not yet completed.

  • Fulfilled: The asynchronous operation has completed, and the promise has a return value.

  • Rejected: The asynchronous operation has failed.


  1. then and catch:
  • .then(): Called when the promise is successfully fulfilled.

  • .catch(): Called when the promise is rejected.

  • .finally(): Called regardless of the success or failure of the promise.