0

我想執行多個回調,同時在數組中存儲值,但在結束數組返回空。如何在節點js中多次異步回調後保持數組值?

這裏是我的代碼:

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

我哪裏做錯了嗎?任何人都可以建議我嗎 或者,如果在nodejs中有其他選擇。

謝謝

回答

0

該回調被稱爲提前。請嘗試以下操作:

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

不幸的是,再次沒有得到所有sheetData結尾。它是空的。 – uday214125

+0

當我將這個(doc!=='')改爲(doc!='')它的工作正常時, 謝謝@Chris Satchell – uday214125

+0

使用'!doc'可能也會工作得很好 –