4

I am learning node.js. By now, I have understood what callback means but I am not sure whether a callback is going to be executed synchronously(the caller not proceeding ahead until the callback returns) or asynchronously(the caller making a callback and proceeding ahead with its code).

avinashkrsharma
  • 143
  • 1
  • 9

3 Answers3

3

You cannot really tell by looking at the function invocation. Some callbacks are asynchronous, others are not. You will need to check the docs, it will should be stated there.

Often you can tell them apart by the function's signature. If a callback is expected to be called only once with the result of a computation, and neither the callback nor the function don't return anything, the callback is usually invoked asynchronously (setTimeout, readFile etc). If the function returns the result immediately, the is typically callback invoked multiple times synchronously (Array::sort, Array::map) and yields valuable values. Of course, the exception proves the rule, and sometimes you cannot tell easily, e.g. setInterval vs Array::forEach (both return nothing, and invoke the callback multiple times).

Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
1

I'll try to rephrase your question, because there is a lot confusion in "Async function call" and "Async IO" terminology.

Let's write it that way: Given code below, and without looking at "foo" source code, can we run some test to say if output is going to be "Line 1\nLine2" or "Line 2\nLine1"?

var t1 = asyncTestCapture();
foo(function() {
   console.log("Line 1");
});
console.log("Line 2");
var out12vsOut21 = asyncTestVerify(t1);

Answer number 1: don't try to rely on this order with exception for a well known standard function with callback parameters (Array's forEach, map, etc, String replacer, JSON reviver)

Answer number 2: (note that I tested the code very briefly and it's node.js specific, but I believe it can answer "out12vsOut21" question. Also note that I'm using undocumented node functions)

function asyncTestCapture() {
  return {
    activeHandles:  process._getActiveHandles(),
    activeRequests: process._getActiveRequests()
  };
}

function asyncTestVerify(handles1) {
  var handles2 = asyncTestCapture();
  return handles2.activeHandles === handles1.activeHandles && handles2.activeRequests === handles1.activeRequests
}

I'll repeat again: if you need the code above there is something wrong in your design. You don't need to know "out12vsOut21" order, build your code the way it does not depend on "async or not foo is"

Andrey Sidorov
  • 24,905
  • 4
  • 62
  • 75
-1

You can use a flag for that:

var async = false;

someFunction(function () {
  console.log(async ? 'async' : 'sync');
});

async = true;
vkurchatkin
  • 13,364
  • 2
  • 47
  • 55