Promise.race -. , , .
-:
function timeout (promise, duration) {
return Promise.race([
promise,
new Promise((resolve, reject) => {
setTimeout(
() => reject(new Error("Timeout")),
duration
)
})
]);
}
timeout(fetch("something"), 5000)
.then(() => {
})
.catch(err => {
));
, , Promise (, , ):
Promise.prototype.timeout = function (duration) {
return Promise.race([
this,
new Promise((resolve, reject) => {
setTimeout(
() => reject(new Error("Timeout")),
duration
)
})
]);
};
fetch("something")
.then(() => ...)
.timeout(5000)
.catch(err => ...);