I have a function that generates a Promise. Afterward, I have another function that constructs an array of these promises for future utilization. It is important to note that I do not want to execute the promises within the array building function since sometimes I may need to invoke them in parallel using Promise.all()
, and at other times I may need to call them sequentially within a for loop (as in this scenario).
The function that yields a promise appears as follows:
export const getQueue = async (
date: string,
hour: string,
queue: Queue
) => {
const queueDateTime = getDateTimeFromQueueDateHour(date, hour);
try {
// carry out asynchronous tasks..
return { queue, queueDateTime };
} catch (e) {
// transform error into custom error
if (e instanceof Error) {
throw new GetQueueError(queue, queueDateTime, e.message);
} else {
throw e;
}
}
};
Subsequently, my function for creating an array of promises looks like this (QUEUE_IDS is a constant imported from elsewhere):
export const getAllQueues = (
date: string,
hour: string
) => {
const queuePromises: Promise<{
queue: string;
matchCount: number;
queueDateTime: DateTime;
}>[] = [];
for (const queue in QUEUE_IDS) {
queuePromises.push(
getQueue(date, hour, queue as Queue)
);
}
return queuePromises;
};
Finally, the job function that utilizes the function for generating the promise array is presented below:
const matchHistoryJobFn: JobFn<MatchQueueSuccess> = async (jobId, jobKey) => {
try {
// ...
const queues = getAllQueues(
dateTimeToGetQueueDate(lastMatchIdQueueDate),
"-1"
);
let matchCount = 0;
for (let i = 0; i < queues.length; i++) {
try {
const q = await queues[i];
matchCount += q.matchCount;
} catch (e) {
if (e instanceof GetQueueError) {
log({
jobId,
jobKey,
status: "error",
message: e.message,
currentDateTime: DateTime.utc().toISO(),
meta: { queueDate: e.queueDateTime.toISO(), queue: e.queue },
});
} else {
log({
jobId,
jobKey,
status: "error",
message: e as string,
currentDateTime: DateTime.utc().toISO(),
});
}
}
}
// ...
return {
jobId,
meta: { queueDate: lastMatchIdQueueDate.toISO(), matchCount },
};
} catch (e) {
throw handleJobError(e, jobId);
}
};
In the for loop, I aim to capture any errors occurring with particular queues so that processing can continue with other queues unaffected. Unfortunately, my application keeps crashing due to an unhandled exception originating from 'getQueue'. I am unable to comprehend why this occurs since not only is the invocation of await queue[i]
enclosed in a try-catch block, but the entire job function is also wrapped in its own try-catch.
Edit: On a side note, upon inspecting with the VS Code debugger, it is clear that the error is indeed being thrown by getQueue and not being captured within the for loop.