You could use Promise.race
on the original promise and a timeout promise that rejects, e.g.:
await Promise.allSettled(
promises.map(promise => Promise.race([promise, rejectAfterDelay(5000)])) // **
)
.then(result => result.forEach(d => {
if (d.status === 'fulfilled') {
data.push(d.value)
}
}));
...where rejectAfterDelay
is something like:
const rejectAfterDelay = ms => new Promise((_, reject) => {
setTimeout(reject, ms, new Error("timeout"));
};
Side note: You could use filter
to filter out the rejected promises:
data.push(...
await Promise.allSettled(
promises.map(promise => Promise.race([promise, rejectAfterDelay(5000)]))
).then(result => result.filter(({status}) => status === "fulfilled"))
);
...although I think I'd refactor the "allSettled
within timeout" part into a utility function, e.g.:
const fulfilledWithinTimeout = async (promises, timeout) => {
promises = Array.isArray(promises) ? promises : [...promises];
const all = await Promise.allSettled(promises.map(promise => Promise.race([promise, rejectAfterDelay(timeout)]));
return all.filter(({status}) => status === "fulfilled");
};
then
data.push(...await fulfilledWithinTimeout(promises, 5000));