I’m trying to only have two API calls running at any given time. I’m also trying to recursively call this API immediately after either finishes up until some certain condition (in this example I’ve used i < FOO
). I’m also trying to wait until ALL API calls are finished. So I’m trying to have 2 concurrent API calls at all times but once either finishes then it immediately starts another.
const API_URL = "DUMMY";
const FOO = 10;
async function api(n: number) {
let response = await fetch(API_URL.concat(`/${n}`));
let json = await response.json();
console.log(`${n} Finished!`);
++i;
if (i < FOO) {
return await api(n + 1);
}
return response;
}
var i = 0;
var promises = new Array();
for (let j = 0; j < 2; j++) {
promises[j] = new Promise(async (resolve, reject) => {
const response = await api(j);
resolve(response);
})
}
Promise.all(promises);
I’ve abstracted away some of the details but essentially this is the idea. I create two Promises that resolve once the initial api
call resolves. Since it’s recursive, it should resolve after i > 10
. The code compiles and it calls all API correctly, but the Promise.all
returns immediately.
Thanks in advance!