-
Notifications
You must be signed in to change notification settings - Fork 206
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
refactor(internal): move async helpers using AggregateError to node
- Loading branch information
Showing
4 changed files
with
50 additions
and
42 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// @ts-check | ||
// @jessie-check | ||
|
||
// These tools seem cross platform, but they rely on AggregateError in the error | ||
// handling path, which is currently not available in xsnap | ||
|
||
/** | ||
* @template T | ||
* @param {readonly (T | PromiseLike<T>)[]} items | ||
* @returns {Promise<T[]>} | ||
*/ | ||
export const PromiseAllOrErrors = async items => { | ||
return Promise.allSettled(items).then(results => { | ||
const errors = /** @type {PromiseRejectedResult[]} */ ( | ||
results.filter(({ status }) => status === 'rejected') | ||
).map(result => result.reason); | ||
if (!errors.length) { | ||
return /** @type {PromiseFulfilledResult<T>[]} */ (results).map( | ||
result => result.value, | ||
); | ||
} else if (errors.length === 1) { | ||
throw errors[0]; | ||
} else { | ||
throw AggregateError(errors); | ||
} | ||
}); | ||
}; | ||
|
||
/** | ||
* @type {<T>( | ||
* trier: () => Promise<T>, | ||
* finalizer: (error?: unknown) => Promise<void>, | ||
* ) => Promise<T>} | ||
*/ | ||
export const aggregateTryFinally = async (trier, finalizer) => | ||
trier().then( | ||
async result => finalizer().then(() => result), | ||
async tryError => | ||
finalizer(tryError) | ||
.then( | ||
() => tryError, | ||
finalizeError => AggregateError([tryError, finalizeError]), | ||
) | ||
.then(error => Promise.reject(error)), | ||
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters