What does this do? await asyncForEach(channelIds,async (channelId)=>{ z++;…
- User
What does this do? await asyncForEach(channelIds,async (channelId)=>{ z++; fetchDomainSummaryPayload.body = JSON.stringify({ trafficChannelId: channelId, startDate, endDate:startDate }); try {
if (invokepromises.length < BATCH_LENGTH) { invokepromises.push(...[invokeaxios(backendUrl, fetchDomainSummaryPayload),channelId]); }
else { results = results.concat(await Promise.all(invokepromises)); console.log({reslen:results.length,results:JSON.stringify(results)}) //restart invokepromises = []; invokepromises.concat(...[invokeaxios(backendUrl, fetchDomainSummaryPayload),channelId]); //z++; } } catch (error) { console.log("Invoking failed with:"); console.warn(error); return; } }) - Assistant
This code snippet asynchronously iterates over an array of
channelIdsusing theasyncForEachfunction.For each
channelId, it increments the variablez. It then updates thefetchDomainSummaryPayloadobject with the currentchannelId,startDate, andendDate.The code then checks if the length of the
invokepromisesarray is less than a constant valueBATCH_LENGTH. If it is, it pushes a newinvokeaxiospromise, with thebackendUrlandfetchDomainSummaryPayloadas arguments, as well as thechannelId, into theinvokepromisesarray.If the length of
invokepromisesexceedsBATCH_LENGTH, it waits for all the promises ininvokepromisesto resolve usingPromise.all(). The resolved values are then concatenated to theresultsarray. The code also logs the length ofresultsand the stringifiedresultsobject to the console. - User
The issue is, it doesnt iterate for all of the item in channelIds. It only goes to half of channelIds. Why is that? And what is the fix?
- Assistant
The issue seems to arise from the use of
concat()instead ofpush()when adding the newinvokeaxiospromise to theinvokepromisesarray during the "restart" phase.When
concat()is used, it returns a new array that combines the originalinvokepromisesarray with the new promise. However, this new array is not assigned back to theinvokepromisesvariable, so the originalinvokepromisesarray remains unchanged. This causes the iteration to stop after half of thechannelIdshave been processed because the originalinvokepromisesarray remains empty.To fix this issue, you should replace the line
invokepromises.concat(...[invokeaxios(backendUrl, fetchDomainSummaryPayload),channelId]);withinvokepromises.push(invokeaxios(backendUrl, fetchDomainSummaryPayload),channelId);. This will correctly push the new promise and channelId into theinvokepromisesarray.