JS获取调用者函数并将其重新执行为异步回调
问题描述:
有没有在香草JavaScript(ES5)获取调用函数并在异步调用完成后重新执行它的方法,而无需将其作为回调函数传递?JS获取调用者函数并将其重新执行为异步回调
我在系统上构建一个缓存机制,出于某种原因,我不可能使用承诺,es6的生成器函数等(我认为可以提供任何现代js特性)。
现在,我编码这种方式(这是一个很大的简化版本):
var cache = {};
var cacheCallbackQueue = [];
var theCallerFunction = function(someParam){
loadCache("aDataTarget",function(){
theCallerFunction(someParam);
});
// cache will be used here somehow
// if the needed cache haven't been loaded
// the async cacher should re-execute this caller function after the caching is complete
}
var anotherCallerFunction = function(anotherParam){
loadCache("anotherDataTarget",function(){
anotherCallerFunction(anotherParam);
});
}
var loadCache = function(cacheId,callback){
asyncCall(cacheId, function(result){
cache[cacheId] = result;
cacheCallbackQueue.push(callback);
// is there a way to get the caller function automatically
// without the need to pass it as callback function on the parameter
checkCachingStatus();
})
}
// check if caching is completed,
// if the caching is completed,
// it will execute all previously queued callback function
var checkCachingStatus = function(){
var cachingStatus = "complete";
if(!cache["aDataTarget"] || !cache["anotherDataTarget"]){
cachingStatus = "incomplete";
}
if(cachingStatus === "complete"){
for(var key in cacheCallbackQueue){
cacheCallbackQueue[key]();
}
}
};
theCallerFunction("whatever");
anotherCallerFunction(666);
我不知道如果我编码它,我“JavaScript的路权”打开另一个建议
答
有没有一种方法在香草Javascript(ES2015)获取调用函数并在异步调用完成后重新执行它,而无需将其作为回调函数传递?
没有在标准的JavaScript,没有。有些JavaScript引擎添加了非标准扩展,caller
,但它不是标准的,严格模式是禁止的。
我不知道如果我编码它,我开了另一个建议“的JavaScript路权”
有一对夫妇的“正确的JavaScript的方式”:
- 传递函数为
loadCache
,你说过你不想做的(但你正在做这) - 有无
loadCache
返回一个对象,它提供subcribing事件的手段,并有“回覆尝试“你可以订阅的事件;但订阅的事件是指在通过一个处理函数,这...你说你不想做:-)
说了这么多,这是目前还不清楚为什么会loadCache
需要重新调用调用它的函数。处理这个问题的标准方法是使用承诺(您可以在ES5中使用polyfill; polyfill甚至不是那么大):loadCache
将返回一个承诺,然后调用它的代码将使用它:
var theCallerFunction = function(someParam) {
loadCache(/*...*/)
.then(function(data) {
// Use `data` here
})
.catch(function() {
// Handle failure here
});
// Probably no code here, since you want to wait for the cached information
};
,或者如果调用程序应处理错误:
var theCallerFunction = function(someParam) {
return loadCache(/*...*/)
.then(function(data) {
// Use `data` here
});
};
ES2015是非常现代的,我假定你的意思ES5。 – Keith
***为什么***“无需将其作为回调函数传递”?那是......你怎么这样做,不管怎么样。 –