Movatterモバイル変換


[0]ホーム

URL:


  1. Glossary
  2. Callback function

Callback function

Acallback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

The consumer of a callback-based API writes a function that is passed into the API. The provider of the API (called thecaller) takes the function and calls back (or executes) the function at some point inside the caller's body. The caller is responsible for passing the right parameters into the callback function. The caller may also expect a particular return value from the callback function, which is used to instruct further behavior of the caller.

There are two ways in which the callback may be called:synchronous andasynchronous. Synchronous callbacks are called immediately after the invocation of the outer function, with no intervening asynchronous tasks, while asynchronous callbacks are called at some point later, after anasynchronous operation has completed.

Understanding whether the callback is synchronously or asynchronously called is particularly important when analyzing side effects. Consider the following example:

js
let value = 1;doSomething(() => {  value = 2;});console.log(value); // 1 or 2?

IfdoSomething calls the callback synchronously, then the last statement would log2 becausevalue = 2 is synchronously executed; otherwise, if the callback is asynchronous, the last statement would log1 becausevalue = 2 is only executed after theconsole.log statement.

Examples of synchronous callbacks include the callbacks passed toArray.prototype.map(),Array.prototype.forEach(), etc. Examples of asynchronous callbacks include the callbacks passed tosetTimeout() andPromise.prototype.then(). Here are example implementations ofdoSomething that call the callback synchronously and asynchronously:

js
// Synchronousfunction doSomething(callback) {  callback();}// Asynchronousfunction doSomething(callback) {  setTimeout(callback, 0);}

TheUsing promises guide has more information on the timing of asynchronous callbacks.

See also

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2025 Movatter.jp