Caching JavaScript promise results

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

    I'm going to add a generic method for caching a promise operation. The trick here is that by treating the promise as a real proxy for a value and caching it and not the value we avoid the race condition. This also works for non promise functions just as well, illustrating how promises capture the concept of async + value well. I think it'd help you understand the problem better:

    function cache(fn){
        var NO_RESULT = {}; // unique, would use Symbol if ES2015-able
        var res = NO_RESULT;
        return function () { // if ES2015, name the function the same as fn
            if(res === NO_RESULT) return (res = fn.apply(this, arguments));
            return res;
        };
    }
    

    This would let you cache any promise (or non promise operation very easily:

     var getItems = cache(getAllItemsFromServer);
    
    
     getItems();
     getItems();
     getItems(); // only one call was made, can `then` to get data.
    

    Note that you cannot make it "synchronous".

提交回复
热议问题