Promise: break in the chain

The Promise API has no bound option timeout, but in the presentation of Steve Sanderson at the NDC conference (at 15:31 here https://www.youtube.com/watch?v=9G8HEDI3K6s&feature=youtu.be&t=15m31s ), he presented an elegant timeout with timings in the API. It looks like this:

enter image description here

The great thing about this approach is that the resolution handler still completed (for example, the response was still included in the cache) even after a timeout. He demonstrated this during his presentation (and is available at the YouTube link above). Does anyone know how this chain timeout was implemented?

+4
source share
1 answer

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(() => {
        // ... Operation completed without timeout ...
    })
    .catch(err => {
        // ... An error occurred possibly a timeout ...
    ));

, , Promise (, , ):

Promise.prototype.timeout = function (duration) {
    return Promise.race([
        this,
        new Promise((resolve, reject) => {
            setTimeout(
                () => reject(new Error("Timeout")), 
                duration
            )
        })
    ]);
};

fetch("something")
    .then(() => ...) // This executes before the timeout.
    .timeout(5000)
    .catch(err => ...);
+1

Source: https://habr.com/ru/post/1695327/


All Articles