JavaScript Interview Question #100
What are the main best practices for modern asynchronous JavaScript?
Promises, Async/Await, Fetch & Modern JavaScript Mid-Level Intermediate
Quick Interview Answer
Prefer Promises and async/await for asynchronous control flow, and use try/catch or explicit Promise rejection handling at appropriate boundaries. Run independent I/O concurrently when it improves latency, but do not start uncontrolled amounts of work without considering resource limits.
Detailed Explanation
Prefer Promises and async/await for asynchronous control flow, and use try/catch or explicit Promise rejection handling at appropriate boundaries. Run independent I/O concurrently when it improves latency, but do not start uncontrolled amounts of work without considering resource limits.
Check HTTP status codes when using fetch, support cancellation where requests can become obsolete, avoid swallowing errors, and keep loading/error state explicit in user interfaces. Understand the event loop and Promise scheduling so code does not rely on incorrect timing assumptions.
Code Example
async function loadDashboard(signal) {
try {
const [profile, orders] = await Promise.all([
fetch("/api/profile", { signal }),
fetch("/api/orders", { signal })
]);
if (!profile.ok || !orders.ok) {
throw new Error("Dashboard request failed");
}
return {
profile: await profile.json(),
orders: await orders.json()
};
} catch (error) {
if (error.name !== "AbortError") {
console.error(error);
}
throw error;
}
}