Home > Web Front-end > JS Tutorial > Master JavaScript Promises: Tricky Output Questions Every Developer Must Know! (Part 1)

Master JavaScript Promises: Tricky Output Questions Every Developer Must Know! (Part 1)

Barbara Streisand
Release: 2024-10-08 16:24:30
Original
963 people have browsed it

Master JavaScript Promises: Tricky Output Questions Every Developer Must Know! (Part 1)

JavaScript promises are an essential part of modern web development. They allow us to handle asynchronous operations cleanly and efficiently. However, promises can often behave in surprising ways, especially when combined with event loops and microtasks. This article is Part 1 of a two-part series where we tackle tricky promise-based output questions to sharpen your JavaScript skills.

By the end of this series, you'll have a deeper understanding of how promises interact with the JavaScript event loop. Let’s dive into the first five tricky questions!


Question 1: Basic Promise Resolution

console.log("Start");

const promise1 = new Promise((resolve) => {
  console.log("Promise started");
  resolve("Resolved");
});

promise1.then((result) => {
  console.log(result);
});

console.log("End");
Copy after login

Output:

Start
Promise started
End
Resolved
Copy after login

Explanation:

  1. The first console.log("Start") is executed.
  2. The promise executor runs immediately, logging Promise started.
  3. The .then() block is scheduled as a microtask after the current code finishes executing.
  4. console.log("End") runs next.
  5. Finally, the .then() callback logs Resolved when the microtask queue is processed.

Question 2: Nested Promises

const promise2 = new Promise((resolve) => {
  resolve("Resolved 1");
});

promise2.then((result) => {
  console.log(result);
  return new Promise((resolve) => {
    resolve("Resolved 2");
  });
}).then((result) => {
  console.log(result);
});
Copy after login

Output:

Resolved 1
Resolved 2
Copy after login

Explanation:

  1. The first .then() logs Resolved 1 and returns a new promise.
  2. The second .then() waits for the returned promise to resolve, logging Resolved 2.

Question 3: Chained Promise with Immediate Resolution

const promise3 = Promise.resolve();

promise3
  .then(() => {
    console.log("Then 1");
  })
  .then(() => {
    console.log("Then 2");
  })
  .then(() => {
    console.log("Then 3");
  });
Copy after login

Output:

Then 1
Then 2
Then 3
Copy after login

Explanation:

  1. When a promise is immediately resolved (Promise.resolve()), its .then() handlers are queued in the microtask queue.
  2. Each .then() returns a new promise that resolves after its callback runs, resulting in a sequential execution of Then 1, Then 2, and Then 3.

Question 4: Rejection Handling

const promise4 = new Promise((_, reject) => {
  reject("Error occurred");
});

promise4
  .then(() => {
    console.log("This will not run");
  })
  .catch((error) => {
    console.log("Caught:", error);
  })
  .then(() => {
    console.log("This will still run");
  });
Copy after login

Output:

Caught: Error occurred
This will still run
Copy after login

Explanation:

  1. The promise is rejected with the message "Error occurred".
  2. The .catch() block catches the error and logs Caught: Error occurred.
  3. After .catch(), the next .then() still runs because it’s treated as a resolved promise unless the catch throws again.

Question 5: Mixing Async/Await with Promises

async function asyncFunc() {
  console.log("Async function started");
  return "Async result";
}

asyncFunc().then((result) => {
  console.log(result);
});

console.log("Synchronous log");
Copy after login

Output:

Async function started
Synchronous log
Async result
Copy after login

Explanation:

  1. When asyncFunc is called, it immediately logs Async function started.
  2. The return value of an async function is a promise, so the .then() is scheduled as a microtask.
  3. console.log("Synchronous log") runs next, followed by the resolution of the promise which logs Async result.

Conclusion:

In this first part, we covered the basics of JavaScript promises and explored how promise resolution, chaining, and rejection handling work. Understanding the event loop and microtask queue is crucial to mastering promises, and these questions highlight that. Stay tuned for Part 2, where we’ll dive into more advanced promise behaviors, including Promise.race, Promise.all, and more!

Key Takeaways:

  • Promise resolution is always asynchronous, and .then() handlers are processed after the current synchronous code.
  • Each .then() returns a new promise, allowing chaining.
  • catch() handles promise rejections, and subsequent .then() calls will still be executed.

Stay tuned for Part 2 of this series, where we tackle more advanced promise tricks!

The above is the detailed content of Master JavaScript Promises: Tricky Output Questions Every Developer Must Know! (Part 1). For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template