Node.js is built to handle many tasks at once without waiting for each to finish. Why is this important?
Think about how Node.js handles many users at the same time.
Node.js uses a single thread to handle many tasks. Async patterns let it start a task and move on without waiting, so it doesn't get stuck.
Consider this code snippet that reads a file synchronously in Node.js. What is the effect on the server?
const fs = require('fs'); console.log('Start'); const data = fs.readFileSync('file.txt', 'utf8'); console.log(data); console.log('End');
Think about what 'Sync' means in the function name.
readFileSync blocks the single thread until the file is fully read, stopping other tasks from running during that time.
Look at this Node.js code using async patterns. What will be printed first?
console.log('A'); setTimeout(() => console.log('B'), 0); Promise.resolve().then(() => console.log('C')); console.log('D');
Remember the order of synchronous code, microtasks, and macrotasks.
Console logs 'A' and 'D' synchronously. Promise.then runs next (microtask), printing 'C'. setTimeout runs last (macrotask), printing 'B'.
Choose the code snippet that correctly uses async/await to read a file.
Remember that await can only be used inside async functions and with promises.
Option C correctly imports fs/promises, uses async function, and awaits the promise returned by readFile.
Consider this Node.js async function. Why does it never log 'Done'?
async function process() { setTimeout(() => { console.log('Timeout done'); }, 1000); console.log('Start'); await new Promise(() => {}); console.log('Done'); } process();
Look at the promise passed to await. Does it ever finish?
The promise passed to await has an empty executor and never calls resolve or reject, so the function waits forever.