To wait for all your async code to finish before running them again you have to execute the next round inside the .then()
. Since you are already using promises you only need to return the chain:
function executeAsyncCode() {
return doAsync1().then(doAsync2).then(doAsync3)...
}
Then executeAsyncCode()
can itself continue on a .then()
:
executeAsyncCode()
.then(function(){
console.log('finished');
});
So, two loops would be:
executeAsyncCode()
.then(executeAsyncCode);
Five loops would be:
executeAsyncCode()
.then(executeAsyncCode)
.then(executeAsyncCode)
.then(executeAsyncCode)
.then(executeAsyncCode)
.then(executeAsyncCode);
To do an infinite loop, you can use the old setTimeout-style loop trick used by javascript animators and game programmers. This is an infinite loop:
function executeAsyncCode() {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(executeAsyncCode);
}
Alternatively:
function executeAsyncCode() {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(function(){
executeAsyncCode();
});
}
This second syntax allows us to write conditional loops:
function executeAsyncCode() {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(function(){
if (we_should_loop()) {
executeAsyncCode();
}
});
}
We can also structure our code so that we can pass the loop condition as an argument. This is a simple countdown loop:
function executeAsyncCode(count) {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(function(){
count--;
if (count) {
executeAsyncCode(count);
}
});
}
So we can call it like this:
executeAsyncCode(5); // runs 5 loops
This emulates a simple for loop:
function executeAsyncCode(start, end) {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(function(){
start--;
if (start < end) {
executeAsyncCode(start,end);
}
});
}
executeAsyncCode(0, 20); // loops 20 times
This tries to emulate most of the features of a for loop:
function executeAsyncCode(x, checkfunction, incrementfunction) {
if (checkfunction(x)) {
doAsync1()
.then(doAsync2)
.then(doAsync3)
.then(function(){
executeAsyncCode(incrementfunction(x));
});
}
}
So you can sort of call it like a for loop:
// loops 10 times like a for loop:
executeAsyncCode(0, function(i){return i<10}, function(i){return i++});