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

时间:2017-06-03 23:56:26

标签: javascript node.js http

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

但是,如果快速连续有多个请求,则源图像尚未在本地保存,并且会执行不必​​要的检索。

在将源图像缓存之前,将传入的请求推迟到有什么好方法,前提是它当前已被检索?

我目前正在从入站请求流中一直使用Node.js流,将其传递给我的缓存和转换逻辑,并将其传递给出站流。

1 个答案:

答案 0 :(得分:2)

您可以缓存承诺,以便所有对同一资源的传入请求只需要一次旅行,避免充斥数据库或某些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');
 });

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