Caching JavaScript promise results

前端 未结 6 876
独厮守ぢ
独厮守ぢ 2021-01-03 01:55

I would make one call to the server to get a list of items. How do I make sure that only one call is made and the collections is processed only once to create a key value ma

6条回答
  •  悲哀的现实
    2021-01-03 02:24

    A promise is stateful, and as soon as it's fulfilled, its value cannot be changed. You can use .then multiple times to get its contents, and you'll get the same result every time.

    The getAllItemsFromServer function returns a promise, the then block manipulates the responses and returns the itemMap, which is wrapped in a response (promise chaining). The promise is then cached and can be used to get the itemMap repeatedly.

    var itemsPromise = getItems(); // make the request once and get a promise
    
    function getItems(){
        return getAllItemsFromServer().then(function(data){
           return data.reduce(function(itemMap, value){
              itemMap[value.key] = value;
              return itemMap;
           }, {});
        });
    }
    
    //need to get the values from various places, using a loop here  
    //to make multiple calls
    var itemKeys = ['a', 'b', 'c'];
    itemKeys.forEach(function(key){
        itemsPromise.then(function(data){ 
            return data[key];
        }).then(function(value) {
           console.log('item for key=' + value);
        });
    });
    

提交回复
热议问题