如何防止在node.js中两次调用相同的URL
我有数量的电话作为后端。 其中一些是相同的URL。 我正在caching结果。 但我的问题是,如果我立即用同一个URL调用loadCached两次(或几次),它实际上也会调用两次提取,因为在第一次提取被parsing之前,caching没有url。 所以,只有当一个抓取成功完成(=已解决)时,caching才起作用。 我怎样才能改进代码,等待第一次parsing,以避免重复查询?
function loadCached(url) { let cache = loadCached.cache || (loadCached.cache = new Map()); if (cache.has(url)) { return Promise.resolve(cache.get(url)); // (*) } return fetch(url) .then(response => response.text()) .then(text => { cache[url] = text; return text; }); }
我正在使用promise.all()等待loadCached来解决。
你需要caching整个承诺:
function loadCached(url) { let cache = loadCached.cache || (loadCached.cache = new Map()); let promise; if (cache.has(url)) { promise = cache.get(url) } else { promise = fetch(url) cache.set(url, promise) } return promise .then(response => response.text()) }
还要注意,为了用map设置新值,你需要使用set
方法, cache[url]
是不正确的。