Standard callback sequence with anonymous functions:

//some function
function myFunction() {

  //first level
  collection1.findOne({...}).
  exec(function(error,doc1){

    //second level
    collection2.findOne({...}).
    exec(function(error,doc2){
      
      //third level
      collection3.findOne({...}).
      exec(function(error,doc3){
        //do something with doc1, doc2, doc3
      });
    });
  });
}

Standard callback sequence with named functions:

//some function
function myFunction() {
  
  //first level
  collection1.findOne({...}).
  exec(secondLevel);
}

function secondLevel(error,doc1) {
  collection2.findOne({...}).
  exec(thirdLevel);
}

function thirdLevel(error,doc2) {
  collection3.findOne({...}).
  exec(finalProcessing);
}

function finalProcessing(error,doc3){
  //do something after obtaining doc1, doc2, doc3
}

Disable JS asynchronous feature momentarily in each function using ‘deasync’ module:

var deasync = require("deasync");

function firstLevel() {
  var done = false;

  collection1.findOne({...}).
  exec(function(error,doc1){
    done = true;
  });

  deasync.loopWhile(()=>{ 
    return !done; 
  });
}

function secondLevel() {
  var done = false;

  collection2.findOne({...}).
  exec(function(error,doc2){
    done = true;
  });

  deasync.loopWhile(()=>{ 
    return !done; 
  });
}

function thirdLevel() {
  var done = false;

  collection3.findOne({...}).
  exec(function(error,doc3){
    done = true;
  });

  deasync.loopWhile(()=>{ 
    return !done; 
  });
}

function doSomethingWithDoc1Doc2Doc3(){
  ...
}

function myFunction() {
  firstLevel();
  secondLevel();
  thirdLevel();
  doSomethingWithDoc1Doc2Doc3();
}

Disable JS asynchronous feature momentarily using ‘async’ module:

var async = require("async");

function myFunction() {
  async.series([
    function firstLevel(){
      collection1.findOne({...}).
      exec(function(error,doc1){
        ...
      });
    },
    function secondLevel(){
      collection2.findOne({...}).
      exec(function(error,doc2){
        ...
      });
    },
    function thirdLevel(){
      collection3.findOne({...}).
      exec(function(error,doc2){
        ...
      });
    },
    function doSomethingWithDoc1Doc2Doc3(){
      ...
    }
  ]);
}
Advertisements