Dhananjay Patel Logo
  1. Home
  2. / Blog
  3. / Advance Js Concept
  4. / Lessons
  5. / 3

Promise

A Promise is an object representing the eventual completion or failure of an asynchronous operation. async and await are syntactic sugar for working with promises, making asynchronous code easier to write and read.

Example

// Using Promises
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => resolve("Data received"), 2000);
});
}
fetchData().then(data => console.log(data));
// Using Async/Await
async function fetchAsyncData() {
const data = await fetchData();
console.log(data);
}
fetchAsyncData();

Explanation: The fetchData function returns a promise that resolves after 2 seconds. In the async/await example, the await keyword pauses the function execution until the promise resolves, making the code more straightforward.

Application: Promises and async/await are essential for handling asynchronous operations like API calls, file reading, and more.