Skip to content

Instantly share code, notes, and snippets.

@malisetti
Created August 16, 2021 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malisetti/6c896e0c21177b0bc2a11bc1ffb9d184 to your computer and use it in GitHub Desktop.
Save malisetti/6c896e0c21177b0bc2a11bc1ffb9d184 to your computer and use it in GitHub Desktop.
Execute several functions in a transaction
export type fn = () => Error | null;
export type tfn = { run: fn, revert: fn };
export const doInTransaction = async (i: tfn[]): Promise<Error | null> => {
const reverts: fn[] = [];
for (const fn of i) {
try {
const err = await fn.run();
if (err) {
throw err;
}
reverts.push(fn.revert);
} catch (error) {
const rreverts = reverts.reverse();
for (const rfn of rreverts) {
const err = await rfn();
if (err) {
return err;
}
}
return error;
}
}
return null;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment