Async js challenges
Async js challenges
javascript
Copy code
async function foo() {
console.log("Start");
const res = await Promise.resolve("Resolved");
console.log(res);
}
foo();
console.log("End");
3. Microtasks and Macrotasks: What will be the output here?
javascript
Copy code
setTimeout(() => console.log("Timeout"), 0);
Promise.resolve().then(() => console.log("Promise"));
console.log("Script");
4. Immediate Promise Resolution: Why does this not print "Inside .then" before "Done"?
javascript
Copy code
console.log("Start");
async function test() {
console.log("Async Function");
return "Done";
}
test().then(() => console.log("Inside .then"));
console.log("End");
javascript
Copy code
fetch("https://jsonplaceholder.typicode.com/posts")
.then((res) => res.json())
.then((data) => console.log(data[0].title));
8. Mix of await and .then: Rewrite this using a mix of await and .then. Explain the order of logs:
javascript
Copy code
async function main() {
const res = await fetch("https://jsonplaceholder.typicode.com/posts");
res.json().then((data) => console.log("Title:", data[0].title));
AsyncJS Page 1
res.json().then((data) => console.log("Title:", data[0].title));
console.log("After fetch");
}
main();
javascript
Copy code
async function fetchData() {
const res = await fetch("https://invalid-url");
const data = await res.json();
console.log(data);
}
10. Try-Catch in Nested Async Functions: Write two async functions where one calls the other,
and handle errors at both levels.
11. Promise Rejection: Why does this fail, and how can you fix it?
javascript
Copy code
async function fail() {
return Promise.reject("Error occurred");
}
fail();
javascript
Copy code
async function foo() {
console.log("Async Function Start");
const result = await Promise.resolve("Resolved Value");
console.log(result);
}
console.log("Script Start");
foo();
console.log("Script End");
13. Interleaving Macrotasks: Explain the execution order:
javascript
Copy code
setTimeout(() => console.log("Macrotask 1"), 0);
Promise.resolve().then(() => console.log("Microtask 1"));
setTimeout(() => console.log("Macrotask 2"), 0);
Promise.resolve().then(() => console.log("Microtask 2"));
console.log("Sync Code");
14. Event Loop with Multiple Async Calls: Analyze the order of execution:
javascript
Copy code
async function first() {
console.log("First Function Start");
await second();
console.log("First Function End");
}
AsyncJS Page 2
}
async function second() {
console.log("Second Function");
}
console.log("Global Start");
first();
console.log("Global End");
AsyncJS Page 3