Solved: Resolve an Await function if it takes more than x seconds in Javascript / Node.js


I have an await function() which waits for an external API. Usually, these APIs take 600ms to return data. But sometimes it’s taking around 10 seconds. So how do I write a function so that if it takes more than 1 second, then break that function and resolve anyway (don’t wait for the API)
Here’s the main function code which calls the API.
The actual function:
I want to return success fo the above function
  1. if fetch is success
  2. or if exceeded more than x seconds

Both should return success no matter the real output.

Best Answer:

You can use AbortController to abort the fetch method, inside a setTimeout with 1sec, and if the fetch resolved before the setTimeout callback execute, then clearTimeout

If you have better answer, please add a comment about this, thank you!