An effective utility function is available to handle the mapping process and abstract the type of map
operation:
function convertToNull<P extends Promise<any>[]>(...promises: P): { [K in keyof P]: Promise<Awaited<P[K]> | null> } {
return promises.map((p) => p.catch(() => null)) as never;
}
This function goes through each promise, unwraps it, and wraps it back with a value of null
.
Usage example:
const [valueOfTypeOne, valueOfTypeTwo] = await Promise.all(
convertToNull(
fetchTypeOne(),
fetchTypeTwo(),
)
);
If dealing with an array of promises, simply spread them:
convertToNull(...arrayOfPromises);
If needed, specify the promise array as a tuple for typing purposes:
convertToNull<[Promise<number>]>(...onlyOnePromiseInThisArray);
For more details and testing this solution, visit here.