Skip to content

Instantly share code, notes, and snippets.

@PetukhovArt
Created January 2, 2025 10:49
Show Gist options
  • Save PetukhovArt/c1b0d50a73c30ba1452f7ba19d9e9f52 to your computer and use it in GitHub Desktop.
Save PetukhovArt/c1b0d50a73c30ba1452f7ba19d9e9f52 to your computer and use it in GitHub Desktop.
// Нужно модифицировать метод fetch,
// добавив ему возможность автоматической переотправки запроса в случаи ошибки
const fetchMockReject = () => {
return new Promise((_, reject) => {
setTimeout(() => {
reject("timeout error");
}, 1000);
});
};
//recursion 1
const withRetry1 = (retryCount) => {
let attempts = 0;
return new Promise((resolve, reject) => {
const tryFetch = () => {
attempts++;
return fetchMockReject()
.then((resp) => {
resolve(resp);
})
.catch((err) => {
if (attempts !== retryCount) {
tryFetch();
} else {
reject(err);
}
});
};
tryFetch();
});
};
//recursion 2
const withRetry = async (retryCount) => {
try {
return await fetchMockReject();
} catch (e) {
if (retryCount === 0) {
throw e;
} else {
console.log("retries left", retryCount);
return withRetry(retryCount - 1);
}
}
};
//while
const withRetry2 = (retryCount) => {
let attempts = 0;
return new Promise((resolve, reject) => {
while (attempts < retryCount) {
console.log("retry number", attempts + 1);
attempts++;
fetchMockReject()
.then((resp) => resolve(resp))
.catch((e) => {
if (attempts === retryCount) {
reject(e);
}
});
}
});
};
withRetry(3)
.then(() => console.log("resolved"))
.catch((error) => console.log(error));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment