缓存JavaScript承诺结果 [英] Caching JavaScript promise results

查看:67
本文介绍了缓存JavaScript承诺结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我会打电话给服务器获取一个项目列表。如何确保只进行一次调用,并且只处理一次集合以创建键值映射。

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 map.

var itemMap = {};

function getItems(){
    getAllItemsFromServer().then(function(data){
     data.forEach(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(key){
   var value = getItems().then(function(data){ return data[key]});
   console.log('item for key=' + value);
}


推荐答案

我要添加缓存promise操作的通用方法。
这里的诀窍在于,通过将promise视为值的真实代理并缓存它而不是值,我们避免竞争条件。这也适用于非承诺函数,说明了promises如何很好地捕获异步+值的概念。我认为这有助于您更好地理解问题:

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.

请注意,您无法使其同步

这篇关于缓存JavaScript承诺结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆