> 웹 프론트엔드 > JS 튜토리얼 > Master JavaScript 약속: 모든 개발자가 알아야 할 까다로운 출력 질문! (1부)

Master JavaScript 약속: 모든 개발자가 알아야 할 까다로운 출력 질문! (1부)

Barbara Streisand
풀어 주다: 2024-10-08 16:24:30
원래의
954명이 탐색했습니다.

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");
로그인 후 복사

Output:

Start
Promise started
End
Resolved
로그인 후 복사

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);
});
로그인 후 복사

Output:

Resolved 1
Resolved 2
로그인 후 복사

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");
  });
로그인 후 복사

Output:

Then 1
Then 2
Then 3
로그인 후 복사

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");
  });
로그인 후 복사

Output:

Caught: Error occurred
This will still run
로그인 후 복사

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");
로그인 후 복사

Output:

Async function started
Synchronous log
Async result
로그인 후 복사

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!

위 내용은 Master JavaScript 약속: 모든 개발자가 알아야 할 까다로운 출력 질문! (1부)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿