我这里有一个脚本,将表单提交给电子表格。如何在响应失败时对then函数进行重试?
form.addEventListener('submit', e => {
e.preventDefault()
fetch(scriptURL, {
method: 'POST',
body: new FormData(form)
})
.then(response => {
document.getElementById("pasakay-form").reset();
window.location.href='https://digitsorani.net/mulawin-pasahero-success/';
})
.catch(error => alert("Try Again"));
});
下面的代码将一直尝试直到成功
您可能需要调整代码以将尝试次数减少到一个合理的数量
form.addEventListener('submit', e => {
e.preventDefault();
let retries = 5;
const go = () => {
if (retries--) {
fetch(scriptURL, {
method: 'POST',
body: new FormData(form)
})
.then(response => {
document.getElementById("pasakay-form").reset();
window.location.href='https://digitsorani.net/mulawin-pasahero-success/';
})
.catch(go);
} else {
alert("....");
}
};
go();
});
虽然,我在两次尝试之间设置了适当的延迟
form.addEventListener('submit', e => {
e.preventDefault();
let retries = 5;
const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
const go = () => {
if (retries--) {
fetch(scriptURL, {
method: 'POST',
body: new FormData(form)
})
.then(response => {
document.getElementById("pasakay-form").reset();
window.location.href = 'https://digitsorani.net/mulawin-pasahero-success/';
})
.catch(() => pause(500).then(go)) // pause half a second
} else {
alert("....");
}
};
go();
});