Preparing your workspace
Node.js uses an event-driven model where asynchronous operations can complete later without blocking the main JavaScript execution flow.
Backend applications frequently wait for databases, files, network requests, or other I/O operations. Node.js is designed to handle these operations asynchronously. Promises and async/await provide modern ways to write asynchronous code. The event loop coordinates when callbacks and other scheduled work can continue executing. The key idea is that Node.js can handle many waiting I/O operations efficiently, but CPU-heavy JavaScript work can still block the main thread and reduce responsiveness.
An API server can handle many users while their database queries or network requests are waiting to complete.
function wait(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function run() {
console.log('Start');
await wait(1000);
console.log('Finished');
}
run();The terminal prints 'Start' and then prints 'Finished' after about one second.