Javascript 如何在节点js中多次异步回调后保持数组值?
我试图执行多个回调,同时在数组中存储值,但在数组末尾返回空 这是我的密码:Javascript 如何在节点js中多次异步回调后保持数组值?,javascript,arrays,node.js,callback,google-api-nodejs-client,Javascript,Arrays,Node.js,Callback,Google Api Nodejs Client,我试图执行多个回调,同时在数组中存储值,但在数组末尾返回空 这是我的密码: 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 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中有任何其他替代方案
谢谢正在提前呼叫回拨。请尝试以下操作:
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
});
不幸的是,最后还是没有得到所有的数据。它是空的。当我把这个(doc!='')改成(doc!='')它工作正常。谢谢@Chris Satchell