0

J'essaye d'exécuter plusieurs callbacks et en même temps de stocker la valeur dans le tableau, mais à la fin du tableau retourner vide.Comment conserver la valeur de tableau après plusieurs rappels asynchrones dans le noeud js?

Voici mon code:

var sheetData = []; 
async.forEachSeries(req.body.data, function (data, cb) { 
    sheet.find({accountid: req.body.id}, function (err, doc) { 
     if (doc == '') {// get the next worksheet and save it 
      var sheet = new sheet({ 
       accountid: req.body.id, 
       sheetid: data.sheetid 
      }); 

      var jsonData = {}; 
      jsonData.sheetid = data.sheetid; 

      sheet.save(function (err, doc) { 
       if (!err) { 
        sheetData.push(jsonData); // trying to push in array , success 
        console.log("-----sheet data---- : ", sheetData);// data available here 
       } 
      }); 
     } 
    }); 
    cb(); 
}, function() { 
    console.log("-----sheet data---- : ", sheetData);// empty array 
}); 

Où je fais mal? Quelqu'un peut-il me suggérer? Ou, Si une autre alternative dans nodejs.

Merci

Répondre

0

Le rappel est appelé au début. Essayez ce qui suit:

var sheetData = []; 
async.forEachSeries(req.body.data, function (data, cb) { 
    sheet.find({accountid: req.body.id}, function (err, doc) { 
     if (!doc) { 
      return cb(); //sheet exists, call back early 
     } 

     // get the next worksheet and save it 
     var sheet = new sheet({ 
      accountid: req.body.id, 
      sheetid: data.sheetid 
     }); 

     var jsonData = {}; 
     jsonData.sheetid = data.sheetid; 

     sheet.save(function (err, doc) { 
      if (!err) { 
       sheetData.push(jsonData); // trying to push in array , success 
       console.log("-----sheet data---- : ", sheetData);// data available here 
       cb(); // all done, now we can call back 
      } 
     }); 
    }); 
}, function() { 
    console.log("-----sheet data---- : ", sheetData);// lots of sheets 
}); 
+0

Malheureusement, encore une fois ne pas obtenir tous les sheetData à la fin. c'est vide. – uday214125

+0

quand j'ai changé cela (doc! == '') en (doc! = '') Son fonctionnement bien., Merci @Chris Satchell – uday214125

+0

Utiliser '! Doc' fonctionnerait probablement aussi bien –