Код: Выделить всё
const namedPromises = {
database: promise1 as Promise,
someApi: promise2 as Promise,
// ...
} as Record;
Код: Выделить всё
function async someMethod(namedPromises: Record): Promise {
// ...magic...
// i know the result will be more generic but this is for example's sake.
return {
database: promiseSettled1 as PromiseSettledResult,
someApi: promiseSettled2 as PromiseSettledResult,
};
}
Код: Выделить всё
const wrapped = Object.entries(namedPromises).map(([key, promise]) => {
return promise.then(
(value) => ({
key,
result: {
status: 'fulfilled',
value,
} as PromiseFulfilledResult,
}),
(reason) => ({
key,
result: {
status: 'rejected',
reason,
},
}),
);
});
< /code>
Я предоставляю ключ как разрешенные, так и отклоненные результаты, чтобы узнать, какое обещание это относится. < /p>
Вот основная проблема. Этот мета -результат также является обещанием
Код: Выделить всё
wrapped
dependencyHealthReporters: Record,
timeoutPerDependency: number = 1000, // ms
): Promise {
const withTimeout = (
key: string,
promise: Promise,
): Promise => {
const timeoutPromise = new Promise((_, reject) =>
setTimeout(
() =>
reject(new Error(`Timeout exceeded: ${timeoutPerDependency}ms`)),
timeoutPerDependency,
),
);
// allow dependencies to timeout individually to increase resilience of health function.
return Promise.race([promise, timeoutPromise]).then(
(value) => ({
key,
result: {
status: 'fulfilled',
value,
} as PromiseFulfilledResult,
}),
// this will be either the timeout rejection, or the rejected promise.
(reason) => ({
key,
result: {
status: 'rejected',
reason,
},
}),
) as Promise;
};
const settledEntries = await Promise.allSettled(
Object.entries(dependencyHealthReporters).map(
([dependencyName, promise]) => withTimeout(dependencyName, promise),
),
);
return Object.fromEntries(
settledEntries
// we rely on all promises being fulfilled at the `withTimeout` function for this logic to work.
.filter((topSettled) => topSettled.status === 'fulfilled')
.map(({ value }) => [
value.key,
// either returns the resolved health info or converts the rejection error into an
this.healthInfoFromSettledResult(value.result),
]),
);
}
< /code>
Некоторые связанные мысли: < /p>
- Есть ли способ сказать: «Поверьте мне, все это решает?» кроме того, что неизвестно, так как обещание > Если я уверен в гарантированном урегулировании обернутых обещаний, что -то кажется вонючим по этому поводу.
Подробнее здесь: https://stackoverflow.com/questions/794 ... d-promises