How to call function after completion of async functions inside loop?

后端 未结 2 1335
南方客
南方客 2021-01-06 20:46

I have a forEach loop in NodeJS, iterating over a series of keys, the values of which are then retrieved asynchronously from Redis. Once the loop and retrieval has complete,

2条回答
  •  醉话见心
    2021-01-06 21:17

    No lib is needed. Easy as pie, it's just an async loop. Error handling is omitted. If you need to do a parallel async loop use a counter.

    exports.awesomeThings = function(req, res) {
        client.lrange("awesomeThings", 0, -1, function(err, awesomeThings) {
            var len = awesomeThings.length;
            var things = [];
            (function again (i){
                if (i === len){
                    //End
                    res.send(JSON.stringify(things));
                }else{
                    client.hgetall("awesomething:"+awesomeThings[i], function(err, thing) {
                        things.push(thing);
    
                        //Next item
                        again (i + 1);
                    })
                }
            })(0);
    });
    

提交回复
热议问题