for loop over event driven code?

前端 未结 3 1323
孤街浪徒
孤街浪徒 2021-01-21 23:18

In a redis datastore I have a list of keys, I want to iterate over that list of keys and get those values from redis. The catch is I am using an event driven language, javascri

3条回答
  •  灰色年华
    2021-01-21 23:39

    Declare an object variable before you dispatch your calls within the for loop. Each call can than add its result into the object.

    You then need code to wait for all calls to be done. This might help you: https://gist.github.com/464179

    Example:

    function getAll(callback) {
    
        var results = [];
    
        var b = new Barrier(2, function() {
            // all complete callback
            callback();
            }, function() {
            // Aborted callback, not used here
        });
    
        var list = redis.lrange(lrange('mykey', 0, -1);
        for ( var i = 0; i < list.length; i+= 1 ) {
            //dispatch your call
            call(function(foo){
                results.push(foo);
                b.submit();
            });
        }
    }
    

    Please note that call() should be your async database function, that executes the callback on result.

提交回复
热议问题