Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to JavaScript

JavaScript Promises and Async/Await Deep Dive

JavaScript3,200 viewsBy Muhammad Fareed
javascriptpromisesasync-awaitasynchronous

JavaScript Promises and Async/Await

Deep dive into JavaScript Promises and async/await for handling asynchronous operations.

Promises

Creating Promises

const promise = new Promise((resolve, reject) => {
  setTimeout(() => {
    resolve('Success!');
  }, 1000);
});

Promise Methods

promise
  .then(result => console.log(result))
  .catch(error => console.error(error))
  .finally(() => console.log('Done'));

Async/Await

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error:', error);
  }
}

Promise.all()

const [user, posts] = await Promise.all([
  fetch('/api/user').then(r => r.json()),
  fetch('/api/posts').then(r => r.json())
]);

Error Handling

async function handleErrors() {
  try {
    const data = await fetchData();
  } catch (error) {
    // Handle error
  }
}

Best Practices

  • Always handle errors with try/catch
  • Use Promise.all() for parallel requests
  • Avoid nested promises (callback hell)
  • Use async/await for cleaner code