Is there any way to not use await inside loop for following code?
const redirects = ['redirectId1'];
for (let i = 0; i < redirects.length; i++) {
const promiseResult = await anAsyncFunction(redirects[i]);
if (promiseResult.redirects) {
redirects.forEach(newRedirect => {
if (!redirects.includes(newRedirect)) redirects.push(newRedirect);
});
}
}
I've tried using Map
const redirects = ['redirectId1'];
const promiseArr = redirects.map(async redirect => {
const promiseResult = await anAsyncFunction(redirect);
if (promiseResult.redirects) {
redirects.forEach(newRedirect => {
if (!redirects.includes(newRedirect)) redirects.push(newRedirect);
});
}
});
await Promise.all(promiseArr);
but in doing so, code executes further before newRedirect is pushed to redirects array
thus not calling anAsyncFunction for new added value.
I want to know if there any possible way to achieve this?
If the idea is to send out each request as soon as possible, without waiting for earlier requests to resolve first, you can use a recursive async function that calls itself when the result contains redirects:
If you also need to use the populated outer
redirectsarray later, then: