When I run the following code:
b = async attempt => {
if (attempt == 5) {
return;
}
console.log("Starting attempt:", attempt);
b(attempt + 1).then(() => {
console.log("Finished attempt:", attempt);
});
};
b(0);
The output is:
Starting attempt: 0
Starting attempt: 1
Starting attempt: 2
Starting attempt: 3
Starting attempt: 4
Finished attempt: 4
Finished attempt: 3
Finished attempt: 2
Finished attempt: 1
Finished attempt: 0
However, I want to call another promise a
before each recursive call as follows:
a = Promise.resolve();
b = async attempt => {
if (attempt == 5) {
return;
}
console.log("Starting attempt:", attempt);
a.then(() => {
b(attempt + 1);
}).then(() => {
console.log("Finished attempt:", attempt);
});
};
b(0);
Now the output is:
Starting attempt: 0
Starting attempt: 1
Starting attempt: 2
Finished attempt: 0
Starting attempt: 3
Finished attempt: 1
Starting attempt: 4
Finished attempt: 2
Finished attempt: 3
Finished attempt: 4
How can I modify the second code block to ensure that the output is the same as the first code block?