有沒有在香草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的路權」打開另一個建議
ES2015是非常現代的,我假定你的意思ES5。 – Keith
***爲什麼***「無需將其作爲回調函數傳遞」?那是......你怎麼這樣做,不管怎麼樣。 –