xSKILLby Infirals
Register

JavaScript for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Practice questions: async JavaScript

Async JavaScript18 min readLesson 4 of 4

Work out each output before running the snippet. The timer and promise examples are short enough to trace by hand, and the fetch example uses a data URL so it runs without a server.

4.1 Q1 Why does a setTimeout(..., 0) callback run after the last synchronous line?

Answer (English): The timer callback is placed on the task queue, and the event loop processes that queue only after the current script finishes. A zero delay means the callback has no added wait, not that it runs immediately. Promise microtasks are drained before the next timer task.

Hinglish: Timer callback task queue mein jata hai, aur event loop us queue ko current script khatam hone ke baad hi process karta hai. Zero delay ka matlab hai ki extra wait nahi, turant chalna nahi. Promise ke microtasks agli timer task se pehle chalte hain.

4.2 Q2 What are the three states of a promise?

Answer (English): Pending, fulfilled and rejected. Pending means the value is not ready, fulfilled means the promise produced a value, and rejected means it produced a reason for failure. A promise moves once from pending to one of the settled states and never changes afterwards.

Hinglish: Promise ke teen states hain: pending, fulfilled aur rejected. Pending ka matlab value abhi nahi mili, fulfilled matlab value mil gayi, aur rejected matlab failure ka reason mila. Promise pending se ek hi baar settled state mein jata hai, phir nahi badalta.

4.3 Q3 How does a promise chain pass values from one step to the next?

Answer (English): Each then returns a new promise, and the value returned by its handler becomes the fulfilled value of that new promise. The next then receives it. If a handler throws, the remaining success handlers are skipped and the nearest catch receives the error.

Hinglish: Har then naya promise return karta hai, aur handler ka return value us naye promise ki fulfilled value banta hai. Agla then wahi value paata hai. Handler mein throw hua to baaki success handlers skip hote hain aur nearest catch error pakadta hai.

4.4 Q4 What is the difference between Promise.all and Promise.allSettled?

Answer (English): Promise.all fulfils with an array of all values when every promise fulfils, and rejects as soon as one rejects. Promise.allSettled waits for every promise and returns objects describing each outcome, so one failure does not discard the other results.

Hinglish: Promise.all tab fulfil hota hai jab saare promises fulfil hon, aur ek bhi reject hua to turant reject ho jata hai. Promise.allSettled har promise ka intezaar karta hai aur har result ka outcome deta hai, isliye ek failure baaki results ko discard nahi karti.

4.5 Q5 What does an async function return?

Answer (English): It always returns a promise. A returned value fulfils the promise, and a thrown error rejects it. Code after an await inside the function resumes when the awaited promise settles, while the caller continues with the pending promise.

Hinglish: Async function hamesha promise return karta hai. Return kiya value promise ko fulfil karta hai aur throw kiya error reject karta hai. Function ke andar await ke baad ka code tab resume hota hai jab awaited promise settle ho, jabki caller pending promise ke saath aage badh jata hai.

4.6 Q6 Does fetch reject when the server returns a 404?

Answer (English): No. fetch rejects on network-level failures, while HTTP error statuses still fulfil the promise with a Response whose ok property is false. Check response.ok and throw explicitly before reading the body, or the code treats a 404 as success.

Hinglish: Nahi. fetch network-level failure par reject hota hai, jabki HTTP error status par bhi promise fulfil hota hai aur Response ki ok property false hoti hai. Body padhne se pehle response.ok check karke khud throw karo, warna 404 success maan liya jayega.

4.7 Q7 Why should two independent requests not be awaited one after another?

Answer (English): Sequential awaits add the waits together, so two 200 ms requests take about 400 ms. Starting both promises first and awaiting them together takes about the longer of the two. Use Promise.all for a list of independent requests and start them before awaiting.

Hinglish: Sequential await delays ko jod deta hai, isliye do 200 ms requests lagbhag 400 ms lete hain. Dono promises pehle shuru karke saath await karo to time dono mein se zyada wale ke barabar hota hai. Independent requests ke liye Promise.all use karo aur await se pehle shuru karo.

4.8 Q8 What error occurs when JSON.parse reads invalid text, and how should the code handle it?

Answer (English): JSON.parse throws a SyntaxError. Put the parse inside try catch when the text comes from a response or storage, and show a fallback instead of letting the page stop. A Response.json call rejects rather than throwing synchronously, so await it inside the same try block.

Hinglish: JSON.parse invalid text par SyntaxError throw karta hai. Response ya storage se aaya text ho to parse ko try/catch mein rakho aur fallback dikhao, page ko rukne mat do. response.json() synchronously throw nahi karta, woh reject hota hai, isliye usko bhi usi try block mein await karo.

4.9 Q9 Why is a final catch or try catch needed at the end of a promise chain?

Answer (English): An error that reaches the end of a chain with no handler becomes an unhandled rejection, which the browser reports as an error and recent Node versions treat as fatal. A final catch logs the failure and gives the user a message, and async code can use try catch around the awaited calls.

Hinglish: Chain ke end tak error pahuncha aur koi handler nahi mila to woh unhandled rejection banta hai, jo browser error dikhata hai aur naye Node versions mein fatal hota hai. Aakhir mein catch lagao taaki failure log ho aur user ko message mile; async code mein awaited calls ke around try/catch use karo.

4.10 Q10 What is the difference between blocking the thread and awaiting a promise?

Answer (English): Blocking runs a long loop or synchronous call on the main thread, so the page cannot paint or handle input until it ends. Awaiting pauses only the async function and returns control to the event loop, so the page stays responsive while the promise settles.

Hinglish: Blocking matlab main thread par lamba loop ya synchronous call, jisse page paint ya input handle nahi kar sakta jab tak woh khatam na ho. Await sirf async function ko pause karta hai aur control event loop ko de deta hai, isliye promise settle hone tak page responsive rehta hai.

javascript
function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function main() {
  console.log("start");
  await wait(10);
  console.log("done");
}

main();
console.log("after call");

Output

start
after call
done

The five-question quiz for this module is separate. Take it without scrolling back. For any ordering question, write the stack, microtask and timer queues on paper before reading the explanation.