Module 8: Asynchronous JavaScript
Callbacks and Asynchronous Work
Understand callbacks and why asynchronous operations need completion handling.
A callback is a function passed to another function to be called later or at a chosen point. Callbacks are common in event listeners, timers, array methods, and APIs.
function processName(name, callback) {
const normalized = name.trim();
callback(normalized);
}
processName(" Asha ", (value) => {
console.log(`Hello, ${value}`);
});
Not every callback is asynchronous. Array methods such as map invoke their callback immediately during the transformation. Timer callbacks and many I/O callbacks run later.
Callback-based asynchronous code#
Older APIs often use a callback to provide either an error or a result. Nested asynchronous callbacks can become difficult to read when each step depends on the last; this is sometimes called callback hell.
Promises provide a more composable representation of a future result and are covered next. Many modern browser APIs and Node.js APIs use promises.
Do not assume a timer is exact#
setTimeout(fn, 0) does not execute immediately. It schedules a callback to run after the current JavaScript stack finishes and the runtime can process the task. The actual delay can be longer than requested.
Practice#
Write a function that accepts a value and a callback. Use it synchronously first, then use setTimeout to observe that a callback scheduled for later runs after the current statements.