Node js for-loop wait for asynchronous function before next iteration?

前端 未结 2 1287
北海茫月
北海茫月 2020-12-20 01:02

I am making a function that refreshes data every so often and I am having issues with the request chain that I have. The problem is that I have a for-loop running the asynch

相关标签:
2条回答
  • 2020-12-20 01:33

    For completeness, the way to do async things sequentially "by hand" is to use recursion:

    function dothings(things, ondone){
        function go(i){
            if (i >= things.length) {
                ondone();
            } else {
                dothing(things[i], function(result){
                    return go(i+1);
                });
            }
        }
        go(0);
    }
    
    0 讨论(0)
  • 2020-12-20 01:50

    You want the async library.

    For instance,

    for(var i = 0; i < listObj.result.length; i++) {
        varBody.index = i;
        varBody.memberID = listObj.result[i].program_member.id;
        request(
            ...
        , function () {
            // Do more Stuff
        });
    }
    

    Can be written like this instead:

    async.forEachOf(listObj.result, function (result, i, callback) {
        varBody.index = i;
        varBody.memberID = result.program_member.id;
        request(
            ...
        , function () {
            // Do more Stuff
            // The next iteration WON'T START until callback is called
            callback();
        });
    }, function () {
        // We're done looping in this function!
    });
    

    There are lots of handy utility functions like this in async that makes working with callbacks much much easier.

    0 讨论(0)
提交回复
热议问题