Teleporting Goat
Teleporting Goat

Reputation: 467

Asynchronous "for" loop when there is no array

Like the OP from this question, I want to do a for loop, and do something when all the actions have finished.

I checked the answer, and the async library, but all the solutions involve iterating over an array. I don't want to do something "forEach" element of an array, I don't have an array.

What if I just want to do an operation n times ? For example, say I want to insert n random entries in my database, and do something afterwards ? For now I'm stuck with something like :

function insertMultipleRandomEntries(n_entries,callback){
    var sync_i=0;
    for(var i=0;i<n_entries;i++){
        insertRandomEntry(function(){
            if(sync_i==(max-1)){
                thingDoneAtTheEnd();
                callback(); //watched by another function, do my stuff there
            }
            else{
                sync_i++;
                console.log(sync_i+" entries done successfully");
                thingDoneEachTime();
            }
        });
    }
}

Which is absolutely horrendous. I can't find anything like a simple for in async, how would you have done this ?

Upvotes: 1

Views: 66

Answers (1)

marinabilles
marinabilles

Reputation: 78

You can use Promises, supported without a library in node.js since version 4.0.

If the callback function of insertRandomEntry has a parameter, you can pass it to resolve. In the function given to then, you receive an array of parameters given to resolve.

function insertMultipleRandomEntries(n_entries,callback){
    var promises = [];
    for(var i=0;i<n_entries;i++) {
        promises.push(new Promise(function (resolve, reject) {
          insertRandomEntry(function (val) {
            thingDoneEachTime(val);
            resolve(val);
          });
        }));
    }
  
    Promise.all(promises).then(function (vals) {
      // vals is an array of values given to individual resolve calls
      thingDoneAtTheEnd();
      callback();
    });
}

Upvotes: 2

Related Questions