What does asynchronous mean in JavaScript?
Asynchronous code does not run to completion before the next statement. The runtime schedules the work and moves on, and the work happens later, when the runtime gets back to it. That is what lets a page stay responsive while a network request is in flight.
console.log("1 - synchronous");
setTimeout(() => {
console.log("3 - timeout callback");
}, 0);
Promise.resolve().then(() => {
console.log("2 - promise callback");
});
console.log("4 - synchronous again");The output order is the important part, and it surprises people. The synchronous lines run first, in order. Then the promise callback runs, and only after that does the timeout callback run, even though the timer was set up first. That is because the runtime drains all pending microtasks, which is where promise reactions live, before it moves on to the next macrotask such as a timer.
There are two families of asynchronous work in the language. Callback-based APIs, such as setTimeout and addEventListener, schedule a function to be called later. Promise-based APIs return an object you can attach handlers to, and those handlers run in the microtask queue, which means they get to run before the next timer or I/O callback.
One clarification worth making in an interview. Asynchronous does not mean parallel. JavaScript on the browser main thread and on a Node process runs your code on a single thread, so two pieces of your code never execute at the same time. What asynchronous buys you is the ability to wait for something slow without blocking the thread, and the runtime uses that time to handle input, paint the page, or serve other requests.