Node JS async single callback flow (example):

function f1() {
  do_something_1(Abc,Xyz,function(Result){
    f2();
  });
}

function f2() {
  do_something_2(Abc,Xyz,function(Result){
    f3();
  });
}

function f3() {
  do_something_3(Abc,Xyz,function(Result){
    console.log("Done!");
  });
}

Node JS async multiple-callback flow (example):

function f1(List) {
  var All_Count  = List.length;
  var Done_Count = 0;

  for (var Index=0; Index<List.length; Index++) {
    do_something(List[Index],function(Result){
      Done_Count++;
      if (Done_Count==All_Count)
        f2();
    });
  }
}

function f2() {
  //some operations
}

Node JS synchronous function template using Deasync module (example):

var deasync = require("deasync");

function f1() {
  var Done = false;

  do_something_2(Abc,Xyz,function(Result){
    Done = true;
  });

  //use module Deasync to turn this function into 
  //a synchronous function without blocking already running code
  deasync.loopWhile(()=>{
    return !Done;
  });
}

//let f1 and f2... have deasync.loopWhile at tails,
//this function call sequence is kept the same like in code
f1();
f2();
...

Although Deasync module is useful, try to use async callback unless a synchronous function is too necessary.

Advertisements