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!
console.log("Start"); const promise1 = new Promise((resolve) => { console.log("Promise started"); resolve("Resolved"); }); promise1.then((result) => { console.log(result); }); console.log("End");
Start Promise started End Resolved
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); });
Resolved 1 Resolved 2
const promise3 = Promise.resolve(); promise3 .then(() => { console.log("Then 1"); }) .then(() => { console.log("Then 2"); }) .then(() => { console.log("Then 3"); });
Then 1 Then 2 Then 3
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"); });
Caught: Error occurred This will still run
async function asyncFunc() { console.log("Async function started"); return "Async result"; } asyncFunc().then((result) => { console.log(result); }); console.log("Synchronous log");
Async function started Synchronous log Async result
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:
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!