1

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 ?

1 Answer 1

2

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();
    });
}

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. There's something done at every iteration, I wrote only console.log in my example so it made it seem unimportant but it's not, I edited the question. Where does it go ? I need the callback from insertRandomEntry, does it replace resolve or does it go after it ? If I could I'd also like to do something at the end. If I can't it's no big deal, I can still do it after catching the callback but it makes more sense do to in inside the function.
I updated the post to show how additional functions can be called before resolving the promise, and how to collect value results of individual promises.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.