您可以缓存承诺,以便所有到同一资源的传入请求只需要一次旅程,避免泛滥数据库或某些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
将返回相同的承诺,当承诺解决后,两个请求都会得到相同的响应。
- 第三个请求是在照片已经被检索后发出的,因为照片被缓存了,它只会返回响应。
我使用这种技术实现它,它工作!谢谢! – sune
@sune如果它有效,不要忘记将它标记为已接受的答案,以此来帮助他人。 –