Callback

Callbacks are a fundamental concept in asynchronous programming. In JavaScript callbacks are functions that are passed as arguments to other functions and are executed at a later time, typically when a certain event occurs or a task completes.

setTimeout(() => console.log('boom'), 2000)

In most cases, data are passed to the callback function. In nodejs, as a convention, error and result are passed to the callback.

> fs.readdir('/', (err, files) => console.log(files))
undefined
> [
  '.VolumeIcon.icns', '.file',
  '.vol',             'Applications',
  'Library',          'System',
  'Users',            'Volumes',
  'bin',              'cores',
  'dev',              'etc',
  'home',             'opt',
  'private',          'sbin',
  'tmp',              'usr',
  'var'
]

In the browser callback are usually used to listen for DOM events or user interactions:

document.body.onclick = ev => consonsole.log(ev)

// or simply
document.body.onclick = consonsole.log

This is a problem with code above. That is what if the onclick propertie get orverwirtten by another line of code in the code base? Well will get back to this in the next chapter.

Sometimes callbacks can also be synchronous. That is it get called immediately(in the same event loop) after being passed to other functions.

const print = (amount, formatFn) => console.log(`amount is ${formatFn(amount)}`)

print(1/3, amount => amount.toFixed(2))

Callbacks are the fundation of other higher-level asynchronous primitives. We will introduce them in the following chapters.