buttery_cpu
buttery_cpu

Reputation: 45

How would I do a for loop that waits until my function has completed for each loop?

My current code is this:

const fs = require('fs');
var file = fs.readFileSync('file.txt').toString().split("\n");

for(i in file) {
    var [thing1, thing2, thing3] = file[i].split(":");
    myfunction(thing1, thing2, thing3);
}

This executes a function for each line in the file with some info from the file. For technical reasons, I can only have the function running once at a time. How can I make the for loop wait for the function to complete before looping again?

Upvotes: 1

Views: 238

Answers (2)

Zeeshan Hassan Memon
Zeeshan Hassan Memon

Reputation: 8325

My approach would be to make myfunction await-able like this:

async function myfunction (thing1, thing2, thing3) {
    // perform your operations here
    return 'done'; // return your results like object or string or whatever
}

So that it can for loop can wait for its completion on each iteration, like this:

const fs = require('fs');
const file = fs.readFileSync('file.txt').toString().split("\n");

// This main function is just a wrapper to initialize code
async function main() {
    for(i in file) {
        let [thing1, thing2, thing3] = file[i].split(":");
        let result = await myfunction(thing1, thing2, thing3);
            console.log(`Result of ${i} returned`);
    }
}

main();

For complete running example clone node-cheat and run node loop-await.js.

Upvotes: 0

David
David

Reputation: 16287

if myfunction is sync one, your code is already working

other wise:

await myfunction(thing1, thing2, thing3);

make sure you add async to your block of code:

(async () => {
  for(i in file) {
     var [thing1, thing2, thing3] = file[i].split(":");
     await myfunction(thing1, thing2, thing3);
}})();

Upvotes: 1

Related Questions