我会向服务器发出一次调用以获取项目列表。如何确保仅进行一次调用并且仅处理集合一次以创建键值映射。
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 视为值的真实代理并缓存它而不是值,我们可以避免竞争条件。这也适用于非 Promise 函数,说明 Promise 如何很好地捕获 async + value 的概念。我认为这会帮助你更好地理解这个问题:
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;
};
}
这将使您可以非常轻松地缓存任何承诺(或非承诺操作):
var getItems = cache(getAllItemsFromServer);
getItems();
getItems();
getItems(); // only one call was made, can `then` to get data.
请注意,您不能使其“同步”.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)