Caching JavaScript promise results

前端 未结 6 991
独厮守ぢ
独厮守ぢ 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:13

    I think what you're really looking for is

    var cache = null; // cache for the promise
    function getItems() {
        return cache || (cache = getAllItemsFromServer().then(function(data){
            var itemMap = {};
            data.forEach(function(value){
                itemMap[value.key] = value;
            });
            return itemMap;
        }));
    }
    
    var itemKeys = ['a', 'b', 'c'];
    itemKeys.forEach(function(key){
        getItems().then(function(data){
            return data[key];
        }).then(function(value) {
            console.log('item for key=' + value);
        }); // notice that you get the value only asynchronously!
    });
    

提交回复
热议问题