【问题标题】:async.whilst with internal callbackasync.while 带有内部回调
【发布时间】:2015-07-13 21:01:09
【问题描述】:

我试图在某个数组的计数小于 50 时进行循环,或者如果循环经过了 14 次以上的迭代。这似乎是 async.whilst 的完美用途。

但是,我的复杂之处在于我的工作函数内部有一个异步查询(数据库查询)。

这是我的代码的简单版本:

var items = [];
var key = 20150713;
var iterations = 0;

async.whilst(
    function(){
        return items.length < 50 || iterations < 14;
    },
    function(callback){
        iterations+=1;

        dbQuery("my query", function(err, res){
            key -=1;
            //add res to items.
            callback();
        });
    },
    function(err){

    });    

当然,这段代码不起作用,因为 dbQuery() 会立即返回,所以 async.whilst 只会吹过 14 次迭代,并在第一个 dbQuery 甚至返回之前返回一个空数组。

我该如何处理,以便 async.whilst 在再次运行之前等待内部函数的返回?

或者是 async.whilst 不适合我的任务?

【问题讨论】:

    标签: node.js


    【解决方案1】:

    您使用正确。只是,从您发布的代码来看,您似乎没有对结果做任何事情:

    async.whilst(
        function(){
            return items.length < 50 || iterations < 14;
        },
        function(callback){
            iterations+=1;
    
            dbQuery("my query", function(err, res){
                key -=1;
                //add res to items.
                callback();
            });
        },
        function(err){
            // this function will be called when whilst completes
            // or when there's an error
    
            if (!err) {
                // use items:
                console.log(items);
            }
            else {
                console.log('OOps.. something went wrong somewhere');
            }
        }
    );
    

    【讨论】:

    • 谢谢。以为最后一个功能只是为了错误。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多