Strengthen your understanding of async error handling in JavaScript, focusing on techniques like try-catch, promise chains, async functions, and common pitfalls. This quiz is designed to help intermediate developers assess their knowledge of managing errors in asynchronous JavaScript code.
Which of the following correctly demonstrates handling an error thrown inside an async function using try-catch?
Explanation: Wrapping the await statement with a try-catch block inside the async function is the standard way to catch errors thrown by awaited promises. Placing try-catch outside the async function when calling it won’t work unless you also use await at that level. Using .catch() inside the function isn’t common practice and reduces readability. Placing await calls outside any function results in syntax errors, making that option incorrect.
Given a promise chain like fetchData().then(processData).then(showData), where should .catch() be placed to handle errors from any stage of the chain?
Explanation: Placing .catch() after the last then() ensures any error thrown anywhere in the chain is caught. Using .catch() after only the first then() would miss errors in later steps. .catch() can't be used before the chain starts, since errors haven't occurred yet. Placing error handling inside processData will only catch errors from that function, not from others in the chain, so it is less comprehensive.
What happens if an error is thrown inside an async function and not caught by a try-catch block?
Explanation: If an error is thrown in an async function without a try-catch block, the function implicitly returns a promise that is rejected with that error. The process does not terminate; instead, unhandled promise rejections may result in warnings. The error is not ignored, nor does the function return undefined in this scenario.
Consider the following code: doSomething().then(() =u003E { throw new Error('Oops'); }).catch(handleError). Which statement best describes what happens if doSomething() resolves successfully?
Explanation: If doSomething() resolves, the next then() block runs and throws an error, which is then caught by the subsequent catch(). Execution does not stop unexpectedly, nor is the error ignored. The catch also handles errors thrown in preceding then() blocks, not just promise rejections from doSomething().
When using several await statements in an async function, what is the risk of placing all of them inside a single try-catch block?
Explanation: If any await statement throws within a try block, execution jumps directly to the catch block, and subsequent await statements are skipped. All errors are not ignored; they are handled by catch. It's not true that only the last error is reported; the first encountered error is. While you can use individual try-catch blocks for fine-grained handling, it’s not strictly required for every await.