2017-08-31 38 views
0

有沒有在香草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的路權」打開另一個建議

+2

ES2015是非常現代的,我假定你的意思ES5。 – Keith

+0

***爲什麼***「無需將其作爲回調函數傳遞」?那是......你怎麼這樣做,不管怎麼樣。 –

回答

0

有沒有一種方法在香草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 
     }); 
};