What is the difference between Asynchronous calls and Callbacks

Viewed 107904

I'm bit confused to understand the difference between Asynchronous calls and Callbacks.

I read this posts which teach about CallBacks but none of the answers addresses how it differs from Asynchronous calls.

Is this Callbacks = Lambda Expressions?

Callbacks are running in a different thread?

Can anyone explains this with plain simple English?

4 Answers

I want to comment paulsm4 above, but I have no enough reputation, so I have to give another new answer.

according to wikipedia, "a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback, or it might happen at a later time as in an asynchronous callback.", so the decorative word "synchronous" and "asynchronous" are on "callback", which is the key-point. we often confuse them with an "asynchronous function", which is the caller function indeed. For example,

const xhr = new XMLHttpRequest();

xhr.addEventListener('loadend', () => {
    log.textContent = `${log.textContent}Finished with status: ${xhr.status}`;
});

xhr.open('GET', 'https://raw.githubusercontent.com/mdn/content/main/files/en-us/_wikihistory.json');
xhr.send();

here, xhr.send() is an asynchronous caller function, while the anonymous function defined in xhr.addEventListener is an asynchronous callback function.

for clarification, the following is synchronous callback example:

function doOperation(callback) {
  const name = "world";
  callback(name);
}

function doStep(name) {
  log.console(`hello, ${name}`);
}

doOperation(doStep)

then, let's answer the specified question:

  1. Is this Callbacks = Lambda Expressions? A: nop, callback is just a normal function, it can be named or anonymous(lambda expressions).
  2. Callbacks are running in a different thread? A: if callbacks are synchronous, they are running within the same thread of the caller function. if callbacks are asynchronous, they are running in another thread to the caller function to avoid blocking the execution of the caller.

A call is Synchronous: It returns control to the caller when it's done.
A call is Async.: Otherwise.

Related