-1

I am waiting for my promise to resolve in an async function using await but I want to wait for only 20 sec. If no response comes in that time (neither positive nor negative from the promise), I want to continue and display 'timeout'. How can I do this?

1 Answers1

4

You can use Promise.race:

const promise1 = func();
const promise2 = new Promise((res, rej) => setTimeout(rej, 20000));

try { 
   await Promise.race([promise1, promise2]);
} catch (e) {
   // time out or func failed
}
hansmaad
  • 18,417
  • 9
  • 53
  • 94