Home > Enterprise >  how to get an async function to restart when encountering errors from an api
how to get an async function to restart when encountering errors from an api

Time:09-06

lets say you have a async function that you want to run continuously. This function retrieves data from an API and Broadcasts responses and every once in a while you receive an error that fetch will fail or there is an issue with the API. Is there a way to have the program restart once it runs into an error.

async function main() {
   await fetch_broadcasting_function()

   setInterval(fetch_broadcasting_function, 11000)
}

main()

CodePudding user response:

Catch the Promise every time you call the function so that

  • Execution doesn't stop if it fails the first time (currently, if the first fetch rejects, you never get to the setInterval call. Alternatively, you can call setInterval first.)
  • You don't run into unhandled rejections (during any fetch)
const tryFetch = () => fetch_broadcasting_function().catch(() => {});
async function main() {
   await tryFetch(); // you can remove this `await` if desired
   setInterval(tryFetch, 11000)
}

main()

CodePudding user response:

I would call it again, with a try/catch/finally

should be something like this:

async function main() {
  try {
    await fetch_broadcasting_function();
    setTimeout(main, 11000);
  } catch (error) {
    console.error('something happened', error);
    main();
  }
}

main()

This way, it will only setTimeout if the await succeeds, else it will call main() again...

  • Related