マスター JavaScript の約束: すべての開発者が知っておくべきトリッキーな出力の質問! (パート1)

Barbara Streisand
リリース: 2024-10-08 16:24:30
オリジナル
937 人が閲覧しました

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!

以上がマスター JavaScript の約束: すべての開発者が知っておくべきトリッキーな出力の質問! (パート1)の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

ソース:dev.to
このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート