How to determine if a callback will execute synchronously or asynchronously?

I am learning node.js. So far, I have understood what a callback means, but I'm not sure if the callback will be executed synchronously (the caller will not continue until the callback returns) or asynchronously (the calling caller will continue its code) .

+4
source share
3 answers

You cannot tell by looking at a function call. Some callbacks are asynchronous, others not . You will need to check the documents, it will be indicated there.

. , , , , (setTimeout, readFile ..). , (Array::sort, Array::map) . , , , . setInterval vs Array::forEach ( ).

+3

, " " " -".

: , "foo", - , , " 1\nLine2" " 2\nLine1"?

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

β„–1: (Array forEach, map .., String replacer, JSON reviver)

β„– 2: ( , node.js , , "out12vsOut21". , node)

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

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

: , - . "out12vsOut21", , "async not foo is"

+1

You can use the flag for this:

var async = false;

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

async = true;
-1
source

All Articles