【问题标题】:How to push to an external array using Async.Whilst如何使用 Async.Whilst 推送到外部数组
【发布时间】:2018-05-17 15:14:44
【问题描述】:

我正在尝试从服务中检索数据并将结果存储在一个数组中以存储为 JSON,由于我正在使用的数据结构,我需要以这种方式嵌套 Async.Whilst

代码:

var async = require('async');
var response = {};
async.whilst(function(){
    if(category <= externalCategory){
        category++;
        return true;
    }else{
        return false;
    }
},function(outerCallback){
    response[category] = [];
    async.whilst(function(){ 
        if(data == "pass"){
            return true;
        }else{
            //retry
            return false;
        }
    },function(callback) {
        var data = {
            //Retrieved data
        };
        response[category].push(data);   
        callback();

    },function () {
        outerCallback();
    });
},function(){
    next(null, response);
}); 

正如我提到的,我想要一个对象以 JSON 格式保存在我的数据库中,如下所示:

预期结果:

response:{
    0:[dataA, dataB],
    1:[dataC, dataD, dataE],
    2:[dataF],
    3:[dataG, dataH]
}

但是,我一直让所有对象都填充了我推送的数组上的最后一个值:

实际结果:

response:{
    0:[dataB, dataB],
    1:[dataE, dataE, dataE],
    2:[dataF],
    3:[dataH, dataH]
}

我是 Node.js 中异步编程的新手,所以我对嵌套异步函数以及为什么会发生这种情况感到非常困惑,有什么帮助或替代方法吗?

【问题讨论】:

    标签: javascript arrays json node.js asynchronous


    【解决方案1】:

    我希望您的问题可以通过使用获取索引值的异步的“eachOfSeries”来解决,这样您就可以避免嵌套异步并且 eachOfSeries 是串行的。所以不用担心异步

    https://caolan.github.io/async/docs.html#eachOfSeries

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-13
      • 2015-10-18
      • 1970-01-01
      • 2015-10-23
      • 2020-05-12
      • 1970-01-01
      • 2016-07-14
      • 2018-02-10
      相关资源
      最近更新 更多