0

I'm interested in the case of wrapping an async operation in a timeout for failure to finish. For example, I'm trying to get data with a fetch function, if after 4 seconds it doesn't arrive, have the function return a result indicating the failure.

I tried to figure it out with Promise.race but still couldn't get it to affect the function's return value.

async timeoutedAwait(awaitedFunc,timeoutInMs){
  setTimeout(()=>{ /* somehow make the function return {success:false,value:undefined} */},timeoutInMs);
  return await awaitedFunc();
}
//....
let result=timeoutedAwait(someFetchOperationFunc,4000);
if(result.success){/* success handling code */}
else{ /* failure handling code */}


user1037607
  • 133
  • 2
  • 12
  • `Promise.race` should do the job. Can you show you attempt with it? – Elias Soares Jun 29 '19 at 18:22
  • Please show us how you tried to use `Promise.race`. Also notice that `timeoutedAwait()` still returns a promise when called, you cannot access the `result` immediately (as usual for async functions). – Bergi Jun 29 '19 at 18:30
  • possible duplicate of [Timeout in async/await](https://stackoverflow.com/q/37120240/1048572) – Bergi Jun 29 '19 at 18:32

1 Answers1

0

something like this?

async function timeoutedAwait(awaitedFunc,timeoutInMs){
  return await Promise.race([awaitedFunc,fail(timeoutInMs)]);
}

var fail = function (time) {
  return new Promise(function(resolve, reject) {
    setTimeout(resolve, time, {success:false,value:undefined});
 });
}

let result=timeoutedAwait(someFetchOperationFunc,4000);
if(result.success){/* success handling code */}
else{ /* failure handling code */}
Nafis Islam
  • 1,483
  • 1
  • 14
  • 34