sql >> Base de Datos >  >> NoSQL >> MongoDB

¿Cómo garantizar que se ejecute una llamada asíncrona antes de regresar de una función en Mongoose?

Aún debe usar async pero necesitas async.waterfall para eso. Esto es lo que debe tener en cuenta:

Un método principal para llamar a su async función:

var getInformation = function(){
  async.waterfall([
    //Array of your functions in order, we will be back here later
  ], function (err) {
       if(err){
         console.log(err);
       }else{
         console.log('Everything OK!');
     }
  );
}

Entonces necesita que sus funciones sean async amigable, eso significa que debe usar devoluciones de llamada y dar sus datos de una función a otra. Algo como esto:

function findUser(callback){
  //Do something
  if('Everything OK'){
    callback(err, yourData); //err should be null if everything is OK and yourData should be the data that you wanna use in your next function. e.g. schoolId 
  }else{
    callback(err); //Something was wrong, "err" should have something different to null
  }
}

function findSchool(callback, schoolId){ //Note that we receive the parameter schoolId here but not in the first function
  //Do something
  if('Everything OK'){
    callback(err, yourData); //err should be null if everything is OK and yourData should be the data that you wanna use in your next function. e.g. schoolName 
  }else{
    callback(err); //Something was wrong, "err" should have something different to null
  }
}

function findStudents(callback, schoolName){
  //Do something
  if('Everything OK'){
    callback(err); //err should be null if everything is OK if this is the last function maybe we don't need to send back more data from here 
  }else{
    callback(err); //Something was wrong, "err" should have something different to null
  }
}

Entonces deberías llamar a tus funciones en tu método principal:

var getInformation = function(){
  async.waterfall([
    findUser,
    findSchool,
    findStudents
    //Note that there is no need to tell the functions the parameters they are sending or receiving here
  ], function (err) {
       if(err){
         console.log(err);
       }else{
         console.log('Everything OK!');
     }
  );
}

Y eso es todo, tiene 3 funciones que deben ejecutarse una después de la otra y no se necesita una devolución de llamada.