繁体   English   中英

如何在节点js中进行多次异步回调后保留数组值?

[英]How to perserve array value after multiple async callback in node js?

我试图执行多个回调,并同时将值存储在array中,但最后数组返回空值。

这是我的代码:

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

我在哪里做错了? 有人可以建议我吗? 或者,如果在Node.js中有其他选择。

谢谢

回调被提早调用。 请尝试以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM