This content originally appeared on DEV Community and was authored by Sudhanshu Gaikwad
JavaScript Promises provide a way to handle asynchronous operations. They represent an operation's eventual completion (or failure) and its resulting value. Let's explore a basic example to understand how Promises work.
Creating a Simple Promise
// Creating a new Promise
const fetchData = new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Hello, this is your data!";
const error = false;
if (!error) {
resolve(data);
} else {
reject("An error occurred while fetching data.");
}
}, 2000); // it will run after 2-second
});
console.log("Fetching data...");
fetchData
.then((result) => {
console.log("Data received:", result);
})
.catch((error) => {
console.error("Error:", error);
})
.finally(() => {
console.log("Operation complete.");
});
In this example:
- We create a new Promise using the Promise constructor, which takes a function with two
parameters: resolve
and reject. - Inside this function, we simulate an
asynchronous
operation usingsetTimeout
. - After 2 seconds, we check if an error occurred
- If no error, we call
resolve(data)
to mark the promise as fulfilled - with the data.
- If there's an error, we call
reject(errorMessage)
to mark the - promise as rejected with an
errorMessage
.
- We handle the promise using .then(), .catch(), and .finally()
- .
then()
is called when the promise is fulfilled. - .
catch()
is called when the promise is rejected. - .
finally()
is called when the promise is settled (either fulfilled or rejected).
When you run the above code, the console will display.
Fetching data...
// After 2 seconds
Data received: Hello, this is your data!
Operation complete.
If you change const error = false; to const error = true;, the output will be
Fetching data...
// After 2 seconds
Error: An error occurred while fetching data.
Operation complete.
This content originally appeared on DEV Community and was authored by Sudhanshu Gaikwad

Sudhanshu Gaikwad | Sciencx (2024-07-27T04:47:45+00:00) JavaScript Promises. Retrieved from https://www.scien.cx/2024/07/27/javascript-promises-3/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.