Promise
A Promise in JavaScript is an object that represents the result of an asynchronous operation.
What does asynchronous
mean in this context?
Synchronous & Asynchronous Communication
Network communication can be broadly divided into Synchronous
and Asynchronous
communication.
Synchronous
communication processes tasks one at a time in order, while holding off on the next task until the previous one is complete. Asynchronous
communication allows multiple tasks to be processed simultaneously, handling the results of tasks as they are completed.
Promise
A Promise represents the result of an asynchronous operation in JavaScript.
As the English word "Promise" suggests, it is a commitment to provide a result at a future point in time. This allows you to wait for an asynchronous operation to complete and then perform additional tasks based on the result (success or failure) of the operation.
Promises are commonly used for handling asynchronous tasks like server communication and events.
const myPromise = new Promise((resolve, reject) => { const isDone = true; if (isDone) { resolve('Task completed'); } else { reject('Task failed'); } }); myPromise .then((result) => { console.log(result); // Task completed }) .catch((error) => { console.log(error); // Task failed });
In this example, a Promise object is created and assigned to the constant myPromise
. The myPromise.then
method registers a callback function (a function that is called within another function) to be invoked when the asynchronous operation completes successfully.
On the other hand, the myPromise.catch
method registers a callback function to be invoked if the asynchronous operation fails.
The Promise calls resolve()
if the operation is successfully completed, or reject()
if it fails.
Characteristics of Promise
- States: A Promise has three states:
-
Pending
: The state when the asynchronous operation has not yet completed. -
Fulfilled
: The state when the asynchronous operation has completed successfully, and the promise returns a value. -
Rejected
: The state when the asynchronous operation has failed, returning a reason for the failure.
2.then
and catch
:
-
.then()
: Called when the promise completes successfully. -
.catch()
: Called when the promise fails. -
.finally()
: Called regardless of the promise's success or failure.
What is the most appropriate word to fill in the blank below?
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help