38
loading...
This website collects cookies to deliver better user experience
const promise1 = new Promise((res) => setTimeout(() => res("promise1"), 1000));
const promise2 = new Promise((res, rej) => setTimeout(() => rej("promise2"), 500));
const result = await Promise.race([p1, p2]);
// promise2
const asyncFunction = async (time, name) => {
await new Promise((res) => setTimeout(res, time));
return name;
}
const result = await Promise.race(
[asyncFunction(1000, "promise1"),
asyncFunction(500, "promise2")
]);
// promise2
const timeout = (promise, time) => {
return Promise.race(
[promise,
new Promise((res, rej) => setTimeout(rej, time))]
);
}
// takes 100ms
const promiseFunction = async () => {
await new Promise((res) => setTimeout(res, 100));
return "promise";
}
const result = await timeout(promiseFunction(), 1000);
// promise
// because it finishes before the timeout of 1000 ms
// timeouts in 100 ms
await timeout(fn(), 50);
// error
const timeout = (promise, time, exceptionValue) => {
let timer;
return Promise.race([
promise,
new Promise((res, rej) =>
timer = setTimeout(rej, time, exceptionValue))
]).finally(() => clearTimeout(timer));
}