1

I would like to handle async timeouts by awaiting the execution and re-executing a function including error handling after it fails.

Pseudo code:

01 call and await async function update()
02 if no error -> continue to line 05
03 sleep for 10000ms
04 Jump to line 01 //call update() again and handle possible errors
05 //continues execution

seems simple, but I cant get the asynchronous part working

Some common structure without any promise handling


let success = false;

while (!success) {
  try{
    update()
    success = true;
  } catch (e) {
    setTimeout(() => {},10000)
  }
}

I know that I should be working with .catch and promises, but cant figure out how.

Thanks for any help and explanations

2
  • To add promise handling, just await the promise returned by the update() call? Commented Jul 11, 2022 at 16:17
  • "setTimeout(() => {},10000)" - that's not how to delay a loop Commented Jul 11, 2022 at 16:18

1 Answer 1

2

Not sure if this is what you're looking for, but here's an example of retrying an async call until success, with a 3 second delay between each attempt:

const wait = timeout => new Promise(resolve => setTimeout(resolve, timeout));

let counter = 0;

async function update() {
  console.log('Updating...');
  await wait(1000)
  if (counter === 3) {
    console.log('Update success');
  } else {
    counter += 1;
    throw new Error('Update failure');
  }
}

async function callUpdateUntilSuccess() {
  try {
    await update();
  }catch(err) {
    console.error(err);
    await wait(3000);
    return callUpdateUntilSuccess();
  }
}

(async () => {
  await callUpdateUntilSuccess();
})();

Sign up to request clarification or add additional context in comments.

4 Comments

Notice that this works only with synchronous update functions
@Bergi It works with async update functions as well. I just updated the example to demonstrate that.
Ah, but you changed return into await - that's all I was complaining about :-)
Ah ok, thanks for pointing that out! I did have to make that change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.