简体   繁体   English

如何处理多个相同的 fetch 请求?

[英]How to deal with multiple fetch requests that are the same?

Let's say that I have multiple eventListeners and some of the use the same fetch request.假设我有多个eventListeners ,其中一些使用相同的获取请求。 Is there a way I can avoid writing multiple fetch requests that get the same data?有没有办法可以避免编写多个获取相同数据的获取请求?

async function foo(){
    let request = await fetch(foo.com/data)
    let response = await request.json()
}

async function foo2(){
    let request = await fetch(foo.com/data)
    let response = await request.json()
}

Cache the response in a global variable, and check the variable before fetching again.将响应缓存在全局变量中,并在再次获取之前检查该变量。

 let foo_data; async function foo() { let response; if (foo_data === undefined) { let request = await fetch('foo.com/data') response = await request.json() foo_data = response; } else { response = foo_data; } } async function foo2() { let response; if (foo_data === undefined) { let request = await fetch('foo.com/data') response = await request.json() } else { response = foo_data; } }

Barmar's answer is good for if the second request comes in after the first request is made, but consider this alternative approach to support two fetch requests made at nearly the same time, which would only actually trigger one real fetch request:如果第二个请求在第一个请求发出后进入,Barmar 的回答是好的,但考虑这种替代方法来支持几乎同时发出的两个fetch请求,这实际上只会触发一个真正的提取请求:

You have an object where each key is a url, and the values are the Promises returned by fetch(url) .您有一个 object,其中每个键都是 url,值是fetch(url)返回的 Promises。 You have some kind of controller class which, when a fetch request comes in, checks if there's already a Promise available for that url. You have some kind of controller class which, when a fetch request comes in, checks if there's already a Promise available for that url. If there is, it gives you back that promise.如果有,它会返回 promise。 If there isn't, it makes one and stores it:如果没有,它会生成一个并存储它:

const cachedPromises = {};

class CachedPromiseController {
    static fetch(url) {
        if (cachedPromises[url]) return cachedPromises[url];
        return CachedPromiseController.newFetch(url);
    }

    static newFetch(url) {
        const promise = fetch(url);
        cachedPromises[url] = promise;
        // maybe you want to delete the cached promise after 30 seconds, so you don't have stale data?
        promise
            .then(async r => {
                await new Promise(r => setTimeout(r, 1000 * 30)); // wait for 30 seconds
                delete cachedPromises[url];
            })
            .catch(e => {
                // delete it immediately if it's an error
                delete cachedPromises[url];
                throw e; // we have to throw this or the consumer won't know there was an error
            })

        return promise;
    }
}

That's a very rough and entirely untested implementation, but it's how i imagined it in my head.这是一个非常粗糙且完全未经测试的实现,但这就是我在脑海中想象的方式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM