1

I have a question about the meaning of callback that is on the MDN, for example array.filter, how to recognize the callback that used in there is sync or async?

j08691
  • 204,283
  • 31
  • 260
  • 272
Sean H
  • 91
  • 7
  • Maybe the fact that it returns the result directly, i.e. you don’t have to wait for events in order to use `[].filter`. You can directly chain it: `[].filter(…).reduce(…).toString()`, etc. – Sebastian Simon Aug 12 '15 at 20:45
  • @Xufox not really. `setTimeout` returns a handle to the timer (timer id), but runs its callback asynchronously. Promises return... well, a promise. But the resolve/reject handlers may execute asynchronously. – Joseph Aug 12 '15 at 20:46
  • "Callback" in that context is perhaps not the best term, since callback suggests something happens (subject of the request), *then* the callback is called. In this case, that's not what happens, the so-called callback *is the subject*. If you're passing it to a function that's using it immediately and the request is not subject to any delay (like `array.filter`), it's going to be run inline. – Jared Farrish Aug 12 '15 at 20:47
  • 1
    why should the callback be async? It's just a function – Dr.Molle Aug 12 '15 at 20:47
  • check this out http://stackoverflow.com/questions/19083357/are-all-javascript-callbacks-asynchronous-if-not-how-do-i-know-which-are?answertab=votes#tab-top – David Chase Aug 12 '15 at 20:47
  • 1
    @JaredFarrish the spec calls it `callbackfn` http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.20 – Joseph Aug 12 '15 at 20:48
  • @JosephtheDreamer - And I think it's not the best term in that context. `:)` Calling it a handler in this situation would be much more explicit to what it's doing. – Jared Farrish Aug 12 '15 at 20:48

1 Answers1

4

You need to figure out the meaning using the following approach: it will be asynchronous if the API itself does asynchronous operations. For example AJAX, Web Sockets, WebRTC, Web Workers are asynchronous APIs.

All other Web browser APIs like Array.prototype functions are all synchronous.

That is, callback doesn't mean asynchronous or synchronous, but just you need to give a function as argument with some input parameters or just a parameterless function.

It would be great if asynchronous functions would be suffixed with Async. For example, setTimeoutAsync(...), or sendAsync, but this just a subjective (but very effective) coding convention not used in JavaScript (it's sad...).

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
  • Node has that convention you mentioned in reverse. Synchronous ones get named explicitly. :) – Joseph Aug 12 '15 at 20:49
  • @JosephtheDreamer Yeah... it does the reverse because Node works on top of the idea of non-blocking I/O so you know that something with `Sync` particle may produce performance issues with high concurrency enviornments... – Matías Fidemraizer Aug 12 '15 at 20:51