caching - How to avoid require avalanches with node.js? -


i want cache data in node server:

rpc data provider this:

var cnt = 0; function rpcdataprovider(areaid) {     return q.delay(100).then(() => {         cnt += 1         console.log("i rpcdataprovider , not fast. requested " + cnt + " times.");         const base = areaid * 10;         var arr = [];         (var = 0; < 10; ++) {             arr.push(base + i);         }         return arr;     }) } 

http server

// cache data var provincelist; var citylist; var countylist;  function getprovincelist() {     if (provincelist && provincelist.length > 0) return q.resolve(provincelist);     return rpcdataprovider(1).then((rv) => {         provincelist = rv;         return rv;     }); }  function getcitylist() {     if (citylist && citylist.length > 0) return q.resolve(citylist);      return getprovincelist().then((provincelist) => {         return q.all(provincelist.map((item) => rpcdataprovider(item))).then(rvs => {             citylist = rvs.reduce((prev, cur) => prev.concat(cur));             return citylist;         });      }); }  function getcountylist() {     if (countylist && countylist.length > 0) return q.resolve(countylist);      return getcitylist().then((citylist) => {         return q.all(citylist.map((item) => rpcdataprovider(item))).then(rvs => {             countylist = rvs.reduce((prev, cur) => prev.concat(cur));             return countylist;         })     }) }  function api1() {     console.log("i http api1");     return getprovincelist(); }  function api2() {     console.log("i http api2");     return getcitylist(); }  function api3() {     console.log("i http api3");     return getcountylist(); }  function api4() {     console.log("i http api4");     return getcountylist(); }  function api5() {     console.log("i http api5");     return getcountylist(); } 

client request:

function httprequest() {     console.log("i client.");     q.all([api1(), api2(), api3(), api4(), api5()]); }  httprequest(); 

the problem parallel requests, cache doest not work!

don't cache promise value. cache promise.

// cache data var provincelist; var citylist; var countylist;  function rpcreduceandconcat(list) {     return q.all(list.map(rpcdataprovider)).then(rvs => {         return rvs.reduce((prev, cur) => prev.concat(cur));     }); }  function getprovincelist() {     if (!provincelist) provincelist = rpcdataprovider(1);     return provincelist; }  function getcitylist() {     if (!citylist) citylist = getprovincelist().then(rpcreduceandconcat);     return citylist; }  function getcountylist() {     if (!countylist) countylist = getcitylist().then(rpcreduceandconcat);     return countylist; } 

Comments

Popular posts from this blog

Spring Boot + JPA + Hibernate: Unable to locate persister -

go - Golang: panic: runtime error: invalid memory address or nil pointer dereference using bufio.Scanner -

c - double free or corruption (fasttop) -