MongoDB
 sql >> Baza danych >  >> NoSQL >> MongoDB

Jak zapewnić wykonanie asynchronicznego wywołania przed powrotem z funkcji w Mongoose?

Nadal powinieneś używać async ale potrzebujesz async.waterfall za to. Oto, co należy wziąć pod uwagę:

Główna metoda wywoływania Twojego async funkcja:

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!');
     }
  );
}

Następnie potrzebujesz funkcji async przyjazny, co oznacza, że ​​powinieneś używać wywołań zwrotnych i przekazywać dane z jednej funkcji do drugiej. Coś takiego:

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
  }
}

Następnie powinieneś wywołać swoje funkcje w swojej głównej metodzie:

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!');
     }
  );
}

I to wszystko, masz 3 funkcje, które powinny być wykonywane jedna po drugiej i nie jest potrzebne żadne piekielne wywołanie zwrotne.



  1. Redis
  2.   
  3. MongoDB
  4.   
  5. Memcached
  6.   
  7. HBase
  8.   
  9. CouchDB
  1. Błąd indeksu MongoDB 2dsphere (nieprawidłowa geometria?)

  2. Zagnieżdżone komentarze w MongoDB

  3. Uwierzytelnianie Java/Mongodb

  4. Jak agregować zagnieżdżoną tablicę wyszukiwania w manguście?

  5. Jak wdrożyć obraz mongoDB Docker w Elastic Beanstalk?