2016-08-08 4 views
0

ich einige Daten in Knoten-Server zwischengespeichert werden soll:Wie vermeidet man Lawinen mit node.js?

rpc Datenprovider wie folgt aus:

var cnt = 0; 
function rpcDataProvider(areaId) { 
    return Q.delay(100).then(() => { 
     cnt += 1 
     console.log("I am rpcDataProvider and I am not so fast. I am requested " + cnt + " times."); 
     const base = areaId * 10; 
     var arr = []; 
     for (var i = 0; i < 10; i ++) { 
      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 am http api1"); 
    return getProvinceList(); 
} 

function api2() { 
    console.log("I am http api2"); 
    return getCityList(); 
} 

function api3() { 
    console.log("I am http api3"); 
    return getCountyList(); 
} 

function api4() { 
    console.log("I am http api4"); 
    return getCountyList(); 
} 

function api5() { 
    console.log("I am http api5"); 
    return getCountyList(); 
} 

Client-Anfrage:

function httpRequest() { 
    console.log("I am client."); 
    Q.all([api1(), api2(), api3(), api4(), api5()]); 
} 

httpRequest(); 

das Problem ist das parallel reque sts, die Cache funktioniert nicht!

Antwort

1

Zwischenspeichern Sie den Versprechenswert nicht. Cache das Versprechen.

// 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; 
} 
Verwandte Themen