Promise in Javascript
Created on: Aug 15, 2024
According to developer.mozilla A Promise is an object representing the eventual completion or failure of an asynchronous operation.
Promises were introduced in JavaScript to address the shortcomings of callback-based asynchronous programming. They offer a more structured, readable, and maintainable way to handle asynchronous operations, with better error handling, easier composition of operations, and more control over program flow.
let fetchData = new Promise(function (resolve, reject) { // Simulate a delay for asynchronous program setTimeout(function () { let success = true; if (success) { resolve("Data fetched successfully!"); } else { reject("Failed to fetch data."); } }, 2000); }); fetchData .then(function (result) { console.log(result); }) .catch(function (error) { console.error(error); }) .finally(function () { console.log("Fetch operation completed."); });
Output
User data fetched Posts data fetched Comments data fetched All operations completed (chained).
Important point for above program
- We can create promise which takes two parameter as a constructor.
resolve
andreject
- If the operation is successful, we call
resolve
with a success message. - If the operation fails, we call
reject
with an error message. .then()
to handle the success case.catch()
to handle the error case..finally()
to perform an action that should occur regardless of the outcome
Let's take a example where we have three functions that returns promise.
function fetchUserData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("User data fetched"); }, 1000); }); } function fetchPostsData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Posts data fetched"); }, 1500); }); } function fetchCommentsData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Comments data fetched"); }, 2000); }); } fetchUserData() .then((userData) => { console.log(userData); return fetchPostsData(); }) .then((postsData) => { console.log(postsData); return fetchCommentsData(); }) .then((commentsData) => { console.log(commentsData); }) .catch((error) => { console.error("An error occurred:", error); }) .finally(() => { console.log("All operations completed (chained)."); });
We can also use Promise.all to handle all asynchronous function.
Promise.all([fetchUserData(), fetchPostsData(), fetchCommentsData()]) .then((results) => { console.log(results[0]); console.log(results[1]); console.log(results[2]); }) .catch((error) => { console.error("An error occurred in one of the promises:", error); }) .finally(() => { console.log("All operations completed (Promise.all)."); });
Suppose fetchPostsData is rejecting, then in this case third function will not be called.
function fetchUserData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("User data fetched"); }, 1000); }); } function fetchPostsData() { return new Promise((resolve, reject) => { setTimeout(() => { reject("Posts data fetched"); }, 1500); }); } function fetchCommentsData() { return new Promise((resolve, reject) => { setTimeout(() => { resolve("Comments data fetched"); }, 2000); }); } fetchUserData() .then((userData) => { console.log(userData); return fetchPostsData(); }) .then((postsData) => { console.log(postsData); return fetchCommentsData(); }) .then((commentsData) => { console.log(commentsData); }) .catch((error) => { console.error("An error occurred:", error); }) .finally(() => { console.log("All operations completed (chained)."); });
Output
User data fetched
An error occurred: Posts data fetched
All operations completed (chained).
Async/await
We can also use async and await to handle asynchronous function.
According to developer.mozilla , async function declaration creates a binding of a new async function to a given name. The await keyword is permitted within the function body, enabling asynchronous, promise-based behavior to be written in a cleaner style and avoiding the need to explicitly configure promise chains.
The await operator is used to wait for a Promise and get its fulfillment value. It can only be used inside an async function or at the top level of a module.
async function fetchAllDataSequential() { try { const userData = await fetchUserData(); console.log(userData); const postsData = await fetchPostsData(); console.log(postsData); const commentsData = await fetchCommentsData(); console.log(commentsData); console.log("All operations completed (sequential async/await)."); } catch (error) { console.error("An error occurred:", error); } } fetchAllDataSequential();
We can run all the three function parallel using Promise.all
async function fetchAllDataParallel() { try { const [userData, postsData, commentsData] = await Promise.all([ fetchUserData(), fetchPostsData(), fetchCommentsData(), ]); console.log(userData); console.log(postsData); console.log(commentsData); console.log("All operations completed (Promise.all)."); } catch (error) { console.error("An error occurred:", error); } } fetchAllDataParallel();