Erwin Manalang
Erwin Manalang

Reputation: 347

Retry function on fail execution

I have here a script that submits a form to a spreadsheet. How can i put a retry on a then function whenever the response fails.

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")); 
});

Upvotes: 0

Views: 151

Answers (1)

Bravo
Bravo

Reputation: 6264

The following will keep trying until it succeeds

You may want to tweak the code to minimize the attempts to a reasonable number

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();
});

although, I'd put in a modest delay between attempts

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();
});

Upvotes: 1

Related Questions