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:
- The first
console.log("Start")
is executed. - The promise executor runs immediately, logging
Promise started
. - The
.then()
block is scheduled as a microtask after the current code finishes executing. -
console.log("End")
runs next. - Finally, the
.then()
callback logsResolved
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:
- The first
.then()
logsResolved 1
and returns a new promise. - The second
.then()
waits for the returned promise to resolve, loggingResolved 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:
- When a promise is immediately resolved (
Promise.resolve()
), its.then()
handlers are queued in the microtask queue. - Each
.then()
returns a new promise that resolves after its callback runs, resulting in a sequential execution ofThen 1
,Then 2
, andThen 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:
- The promise is rejected with the message
"Error occurred"
. - The
.catch()
block catches the error and logsCaught: Error occurred
. - 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:
- When
asyncFunc
is called, it immediately logsAsync function started
. - The return value of an async function is a promise, so the
.then()
is scheduled as a microtask. -
console.log("Synchronous log")
runs next, followed by the resolution of the promise which logsAsync 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!
Top comments (0)