How could I run a function after the completion of a for loop in Node.js?
You can handle the last iteration of the for loop with a conditional checking index.
for(let i = 0; i < 10; i++){
if(i == 10 - 1){
your_function();
}
}
If there is no magic happening then it should be straight forword.
Function:-
function after_forloop() {
//Doing a function.
}
For Loop:-
for (i = 0; i < 50; i++) {
//Doing a for loop.
}
for (i = 0; i < 50; i++) {
//Doing another for loop.
}
after_forloop();
This will call after_forloop
just after both for
loops finishes. Because for
loop is a blocking call, calling of after_forloop()
has to wait.
Note:- If you are doing some async
task in for
loops then the function will be called after loop finished, but the work you are doing in loops might not finished by the time of calling function.
Maybe this helps:
var operationsCompleted = 0;
function operation() {
++operationsCompleted;
if (operationsCompleted === 100) after_forloop();
}
for (var i = 0; i < 50; i++) {
get_line('proxy_full.txt', i, function(err, line, newText){
fs.appendFile('proxy.txt', line + '\n', function (err) {
if (err) throw err;
operation();
});
fs.writeFile('proxy_full.txt', newText, function (err) {
if (err) throw err;
operation();
});
})
}
Admittedly this isn't an elegant solution. If you're doing a whole lot of this you might want to check out something like Async.js.
If you're doing any async operation in the for loop, you can simply keep it like
function after_forloop() {
// task you want to do after for loop finishes it's execution
}
for (i = 0; i < 50; i++) {
//Doing a for loop.
if(i == 49) {
after_forloop() // call the related function
}
}
Still in node.js, instead of making use of for loops with asynchronous functions, you should see the async module. Here's Async.js or you can consider using recursion too.