Skip to content

Instantly share code, notes, and snippets.

@kcoyner
Created January 21, 2021 03:42
Show Gist options
  • Save kcoyner/031579a75d3a98181c9cf9aa71eba461 to your computer and use it in GitHub Desktop.
Save kcoyner/031579a75d3a98181c9cf9aa71eba461 to your computer and use it in GitHub Desktop.
retry when loading a chunk fails
/* If the browser fails to download the module, it'll try again
* 5 times with a 1 second delay between each attempt. If
* even after 5 tries it fails to import it, then an error is thrown.
*/
export function retry(fn, retriesLeft = 5, interval = 1000) {
return new Promise((resolve, reject) => {
fn()
.then(resolve)
.catch((error) => {
setTimeout(() => {
if (retriesLeft === 1) {
// reject('maximum retries exceeded');
reject(error);
return;
}
// Passing on "reject" is the important part
retry(fn, retriesLeft - 1, interval).then(resolve, reject);
}, interval);
});
});
}
import { retry } from '../react_lazy_retry.js'
// Code split without retry login
const ProductList = lazy(() => import("./path/to/productlist"));
// Code split with retry login
const ProductList = lazy(() => retry(() => import("./path/to/productlist")));
// more component stuff
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment