vendredi 7 avril 2017

Running async function form a loop

I'm not looking for any solution in any particular language, I just want to understand what are the good practices in the area of running async tasks from a loop.

This is what I have thought of so far:

var callAcc = 0;
var resultArr = [];

for (var k = 0; k < 20; k++) {
    callAcc ++;

    asyncFunction("variable")
        .then(function (result) {
            resultArr.push(result);

            if (callAcc === resultArr.length) {
                // do something with the resultArr
            }
        })
        .catch(function (err) {
           console.warn(err);
        });
}

At this point, I'm just using a sync variable that will only let me proceed once I have all of the async tasks complete. However, this feels hacky and I was wondering if there was some kind of design pattern to execute aync tasks from a loop

Aucun commentaire:

Enregistrer un commentaire