Skip to content

Commit

Permalink
feat(internal): add async utils from loadgen
Browse files Browse the repository at this point in the history
  • Loading branch information
mhofman committed Sep 16, 2022
1 parent 62526de commit 6ad3a6e
Showing 1 changed file with 56 additions and 0 deletions.
56 changes: 56 additions & 0 deletions packages/internal/src/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,3 +223,59 @@ export const makeMeasureSeconds = currentTimeMillisec => {
};
return measureSeconds;
};

/**
* @param {Error[]} errors
* @param {string} [message]
*/
const makeAggregateError = (errors, message) => {
const err = new Error(message);
Object.defineProperties(err, {
name: {
value: 'AggregateError',
},
errors: {
value: errors,
},
});
return err;
};

/**
* @template T
* @param {readonly (T | PromiseLike<T>)[]} values
* @returns {Promise<T[]>}
*/
export const PromiseAllOrErrors = async values => {
return Promise.allSettled(values).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 makeAggregateError(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 => makeAggregateError([tryError, finalizeError]),
)
.then(error => Promise.reject(error)),
);

0 comments on commit 6ad3a6e

Please sign in to comment.