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

我正在做一个服务,从远程主机检索一张照片,并在将其传递给客户端之前进行一些处理。 它在本地caching检索的源照片,以避免以后再次检索。

但是,如果连续有多个请求,则源图像将不会保存在本地,而是执行不必要的检索。

什么是一个很好的方法来推迟传入的请求,直到源图像被caching,只要它已经被检索?

目前,我正在使用来自入站请求stream的Node.jsstream,通过caching和转换逻辑传递它,并将其传递给出站stream。

您可以caching承诺,以便对同一资源的所有传入请求只需要一次访问,避免泛滥数据库或某些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'); }); } 
  • 对特定照片的第一个请求将执行查找,并将承诺存储在caching中。
  • 第二个请求进入,如果第一个请求的照片还没有被检索, getPhoto将返回相同的承诺,当promise被parsing时,两个请求将得到相同的响应。
  • 第三个请求是在照片已经被检索到之后,因为照片被caching了,它只会返回响应。