As noahnu suggested, you can use Promise.race. You can wrap it in a function that takes a promise.
With some syntax sugar you can use thisOrThat
which takes logic
, a function that takes 2 functions, first
and second
. You can apply logic here as to try the first function and when to try the second (in our case if the first doesn't resolve within a certain time then try the second).
thisOrThat then takes an argument first
that is a function returning a promise (in our case doSomething
.
thisOrThat returns an object that has an or
property that takes a function returning a promise. That parameter is called second
and is passed to logic
as second
(in our case it is doSomethingElse
).
var timeoutPromise =
time =>
promiseFn =>
Promise.race([
promiseFn(),
new Promise(
(_,r)=>
setTimeout(
_=>r("timed out")
,time
)
)
]);
var thisOrThat =
logic =>
first => ({
or:second=>
logic(first)(second)
});
var within75ms = thisOrThat
(first=>second=>
timeoutPromise(75)(first)
.catch(_=>second())
);
var within25ms = thisOrThat
(first=>second=>
timeoutPromise(25)(first)
.catch(_=>second())
);
var doSomething = () =>
console.log("do something called")||
new Promise(r=>setTimeout(x=>r("something"),50));
var doSomethingElse = () =>
console.log("do something else called") ||
new Promise(r=>setTimeout(x=>r("something else"),50));
async function someFunc() {
const doesNotTimeOut =
await within75ms(doSomething).or(doSomethingElse);
console.log("within 75ms resolved to:",doesNotTimeOut);
const doesTimeOut =
await within25ms(doSomething).or(doSomethingElse)
console.log("within 25ms resolved to:",doesTimeOut);
};
someFunc();