skip to Main Content

I’m working in thingsboard Which can use angular, I want to run a function after a for loop complete its execution and in the for loop i have a amount_users variable which gets increase and end of the for loop the function should call by sending the count. Thingsboard does not have Es6 features

var amount_users = 0
for (i = 0; i < data.length; i++) {
    //code 
    amount_users = ++amount_users
}
function_to_get_call_after_for_loop(amount_users).subscribe(
    () => {})
function_to_get_call_after_for_loop(amount_users) {
    //code 
    //api will be called 
}

I want to run the function after a for loop complete its execution and in the for loop i have a amount_users variable which gets increase and end of the for loop the function should call by sending the count .

2

Answers


  1. you can do that by passing it to be a callback instead … this will wait the result then execute the other loop like following:

    var amount_users = 0;
    
    function forLoopWithCallback(data, callback) {
    for (var i = 0; i < data.length; i++) {
        // Your code here
        amount_users++;
    }
    callback(amount_users);
    }
    
    function functionToGetCallAfterForLoop(amount) {
    // Your code here
    // You can make your API call here
    console.log('Function called after for loop with amount:', amount);
    }
    
    forLoopWithCallback(data, function (amount) {
    functionToGetCallAfterForLoop(amount);
    });
    
    Login or Signup to reply.
  2. Your functions execute after the for loop completes, but your for loop likely issues asynchronous operations and those are not yet completed. A very neat solution to this problem is to make sure your asynchronous jobs are promises (see https://www.geeksforgeeks.org/how-to-convert-an-asynchronous-function-to-return-a-promise-in-javascript/)

    and then, after the for loop, instead of calling the functions right away, you can use Promise.all, like

    Promise.all(yourarray).then((values) => {
        //now call your functions
    });
    

    Of course, since Promise.all expects arrays, you will need to create an array before the loop and .push() the promises you want to wait for at each iteration. At the end, Promise.all() is a function that gets an array of promises, waits for all the promises to be fulfilled and once that’s completed the Promise.all function (which is also a promise) will be fulfilled and hence, its then callback will be called.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search