Is there a way to upload multiple file chunks simultaneously and retry each failed chunk five times? I have created an example code in TypeScript Playground that demonstrates this behavior. The code excludes the use of XMLHttpRequest for simplicity.
Here is the sample code:
class FileUploader {
onSuccess: ((this: FileUploader) => void) | null;
onFail: ((this: FileUploader) => void) | null;
constructor() {
this.onSuccess = null;
this.onFail = null;
}
run() {
// Simulation of request failure or success
this.onFail?.();
}
}
async function uploadFile(name: string, retryCount = 0) {
return new Promise<void>(async (resolve, reject) => {
const runner = new FileUploader();
runner.onSuccess = async () => {
await new Promise((res) => setTimeout(res, 500));
resolve();
}
runner.onFail = async () => {
if (retryCount < 5) {
console.log(`Ran ${name}, ${retryCount}`);
const newDelay = Math.pow(2, retryCount) * 100;
await new Promise((res) => setTimeout(res, newDelay));
await uploadFile(name, retryCount + 1);
}
console.log("rejected", name);
reject("error");
}
runner.run();
});
}
async function main() {
try {
await Promise.all([uploadFile("file1"), uploadFile("file2"), uploadFile("file3")])
console.log("success")
}
catch (ex) {
console.log("error")
console.log(ex);
}
}
main();
I am looking to handle errors caught in the main function. Any suggestions on how to achieve this?