Skip to content

Commit

Permalink
Reduce bundle size by optimizing autoRetryOnRejection
Browse files Browse the repository at this point in the history
Reduced the bundle size from almost 3 KB to less than 600 B (5x
reduction) by making autoRetryOnRejection a regular function rather than
async function. Using an async function causes TypeScript to emit
helper code, increasing the bundle size by about 2.4 KB.
Now, we instead just use promise methods and recursion to achieve the
same behavior we had with an async function.
  • Loading branch information
kyarik committed Dec 26, 2020
1 parent 26231ef commit 20311f3
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 13 deletions.
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"circumspect": "^0.1.1"
},
"peerDependencies": {
"react": ">=16.6"
"react": ">=16.6.0"
},
"devDependencies": {
"@size-limit/preset-small-lib": "^4.9.0",
Expand Down Expand Up @@ -72,11 +72,11 @@
"size-limit": [
{
"path": "dist/suspendable.cjs.production.min.js",
"limit": "3 KB"
"limit": "600 B"
},
{
"path": "dist/suspendable.esm.js",
"limit": "3 KB"
"limit": "600 B"
}
]
}
20 changes: 10 additions & 10 deletions src/utils/promise/autoRetryOnRejection/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,26 @@ interface Options {
timeoutMs?: number;
}

const autoRetryOnRejectionRec = <T extends any>(
fn: () => Promise<T>,
options: Required<Options>,
): Promise<T> =>
fn().catch(() =>
wait(options.timeoutMs).then(() => autoRetryOnRejectionRec(fn, options)),
);

/**
* Given a function that returns a promise, keeps calling it until the returned
* promise resolves, returning the result. If the promise rejects, waits
* `timeoutMs` before retrying again.
* @param fn The function that returns a promise.
* @param options Options that can be used to adjust the retry timeout (default 3000).
*/
export const autoRetryOnRejection = async <T extends any>(
export const autoRetryOnRejection = <T extends any>(
fn: () => Promise<T>,
options: Options = {},
) => {
const { timeoutMs = 3000 } = options;

while (true) {
try {
const result = await fn();

return result;
} catch {
await wait(timeoutMs);
}
}
return autoRetryOnRejectionRec(fn, { timeoutMs });
};

0 comments on commit 20311f3

Please sign in to comment.