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

前端 未结 2 1298
北海茫月
北海茫月 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: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.

提交回复
热议问题