我遇到的情况是我正在构建一个基于ES6 JS Promises的数据层,它从网络中获取数据。我在网址内部缓存所有Promise。
除了一件事,一切似乎都很好。我想确保来自网络层的数据是从网络中检索的数据的复制/克隆,我显然不希望在实现Promise的处理程序的客户端代码中到处都这样做。
我想设置它,然后处理程序自动获取缓存数据的副本。
要为此添加一个扭曲,我希望这可以在数据层内的url基础上进行配置,以便一些Promise执行额外的后处理副本,而其他Promg只返回原始结果。
有人可以建议一个正确的实现来实现这一目标吗?我应该提一下,每当新客户要求时,我想获得原始原始结果的新副本。
当前简化的伪实现看起来像这样
getCachedData(url){
if (cache[url]) {
return cache[url];
} else {
var promise = new Promise(function(resolve,reject){
var data = ...ajax get...;
resolve(data);
});
cache[url] = promise;
}
getCachedData(url).then(result=>{
here I want the result to be a copy of data I resolved the original promise with.
});
答案 0 :(得分:2)
结构如下:
function retrieveCopiedData () {
// getDataFromServer is your original Promise
return getDataFromServer().then(function (value) {
// use a library of your choice for copying the object.
return copy(value);
})}
}
这意味着retrieveCopiedData
的所有消费者都将收到retrieveCopiedData
then()
处理程序返回的值。
retrieveCopiedData().then(function (value) {
// value is the copy returned from retrieveCopiedData's then handler
})
您可以根据需要向retrieveCopiedData
添加条件逻辑。
答案 1 :(得分:2)
您似乎只想将克隆过程直接合并到数据层中:
getCachedData(url){
if (!cache[url]) {
cache[url] = new Promise(function(resolve,reject){
var data = ...ajax get...;
resolve(data);
});
}
if (requiresPostProcessing(url))
return cache[url].then(clone);
else
return cache[url];
}
请注意,每次检索数据时都不要克隆数据,而只需要freeze解析您的承诺的对象。