gpt4 book ai didi

javascript - 如果类似的工作已经完成,则推迟 Node.js HTTP 请求

转载 作者:可可西里 更新时间:2023-11-01 17:05:47 25 4
gpt4 key购买 nike

我正在制作一项服务,该服务从远程主机检索照片并在将其传递给客户端之前进行一些处理。它会在本地缓存检索到的源照片,以避免以后再次检索。

但是,如果有多个快速连续的请求,则源图像还没有保存到本地,并且进行了不必要的检索。

如果当前已检索到源图像,那么在缓存源图像之前延迟传入请求的好方法是什么?

我目前从入站请求流一直使用 Node.js 流,通过我的缓存和转换逻辑将其传递到出站流。

最佳答案

您可以缓存 promise ,这样对同一资源的所有传入请求都只需要一次行程,避免淹没数据库或某些 API。

const Cache = {};

function getPhoto(photoId) {

let cacheKey = `photo-${photoId}`;
let photoCache = Cache[cacheKey];

if (photoCache instanceof Promise)
return photoCache; //Return the promise from the cache

let promise = new Promise((resolve, reject) => {

if (photoCache) //Return the photo if exists in cache.
return resolve(photoCache);

return processPhoto(photoId).then(response => {
//Override the promise with the actual response
Cache[cacheKey] = response;
resolve(response);

}).catch(err => {
Cache[cacheKey] = null; //We don't want the rejected promise in cache!
reject();
});

});

if (!photoCache)
Cache[cacheKey] = promise; //Save the promise

return promise;
}

function processPhoto(photoId){

return new Promise((resolve, reject) => {

// Get the image from somewhere...
// Process it or whatever you need

//...
resolve('someResponse');
});

}
  • 对特定照片的第一个请求将执行查找,并将 promise 存储在缓存中。
  • 第二个请求进来,如果第一个请求的照片还没有被检索到,getPhoto 将返回相同的 promise ,当 promise 被解决时,两个请求将得到相同的响应。
  • 第三个请求是在已经检索到照片之后发出的,因为照片已被缓存,所以它只会返回响应。

关于javascript - 如果类似的工作已经完成,则推迟 Node.js HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44349591/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com