Promises and Async/Await

Master asynchronous programming with Promises and async/await syntax.

Present State

Asynchronous programming is essential in JavaScript, especially for operations like network requests or timers. Promises provide a cleaner alternative to callbacks, enabling better error handling and chaining of async operations. ES8 introduced async/await, simplifying asynchronous code and making it appear synchronous.

Code Example

Here's an example showing both Promises and async/await in action:

Promise vs Async/Await

// Using Promises
function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve("Data received!");
    }, 2000);
  });
}

fetchData().then(data => {
  console.log("Promise:", data);
}).catch(error => {
  console.error(error);
});

// Using Async/Await
async function getData() {
  try {
    const result = await fetchData();
    console.log("Async/Await:", result);
  } catch (error) {
    console.error(error);
  }
}

getData();
          

This code demonstrates:

  • Creating and using Promises.
  • Chaining .then() and handling errors with .catch().
  • Writing cleaner asynchronous code using async functions.
  • Awaiting asynchronous results with await.

Description

A Promise represents a value that may be available now, or in the future, or never. It has three states: pending, fulfilled, and rejected.

  • resolve() is called when the async task succeeds.
  • reject() is used when the task fails.

Async/Await is syntactic sugar over Promises, enabling you to write asynchronous code that looks synchronous.

  • async before a function makes it return a Promise.
  • await can only be used inside async functions and waits for the Promise to resolve.

Applications

  • Fetching data from APIs using fetch() or axios.
  • Delaying operations or animations using timeouts.
  • Handling user input events asynchronously.
  • Building real-time applications with WebSockets or Firebase.
  • Executing background tasks or file uploads.

Multiple Choice Questions

Q1: What are the three states of a JavaScript Promise?

  • A. Start, Run, End
  • B. Begin, Finish, Error
  • C. Pending, Fulfilled, Rejected
  • D. Loading, Complete, Failed

Answer: C. Pending, Fulfilled, Rejected

Q2: What does the await keyword do?

  • A. Delays function execution
  • B. Blocks other code execution
  • C. Waits for a Promise to resolve
  • D. Converts sync code to async

Answer: C. Waits for a Promise to resolve

Q3: Which keyword is used to define an async function?

  • A. wait
  • B. promise
  • C. async
  • D. function*

Answer: C. async

Q4: Which method is used to handle errors in a Promise?

  • A. .fail()
  • B. .catch()
  • C. .error()
  • D. .reject()

Answer: B. .catch()