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
you can do that by passing it to be a callback instead … this will wait the result then execute the other loop like following:
Your functions execute after the
for
loop completes, but yourfor
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 usePromise.all
, likeOf 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 afunction
that gets an array of promises, waits for all the promises to be fulfilled and once that’s completed thePromise.all
function (which is also a promise) will be fulfilled and hence, itsthen
callback will be called.