2017-10-28 165 views
2

我試圖通過創建localForage的全局實例來localForage支持添加到pure-form Web組件:有沒有辦法來檢查一個JavaScript函數是否接受回調?

// create a global appStorage object that mimics localStorage API (greater storage) 
window.appStorage = localforage.createInstance({ 
    driver: [ 
     localforage.INDEXEDDB, 
     localforage.WEBSQL, 
     localforage.LOCALSTORAGE 
    ], 
    name: 'product-name', 
    version: 1.0, 
    storeName: 'app' 
}); 

,並通過storage屬性將其分配到的純形式​​的實例:

<pure-form src="path-to-schema.json" storage="appStorage"></pure-form> 

在內部,純粹執行window[self.storage]來獲取存儲對象的句柄,並使用.getItem,.setItem來同步設置和檢索值。

問題是localForage是異步的,意思是.getItem,.setItem期望通過回調返回值。因此我現在的邏輯是行不通的:

// get value from web storage 
var storedContent = window[self.storage].getItem('item-key'); 

我知道我可以換一個無極的電話,但因爲它代表的純形式不需要承諾,我討厭只想補充一點,依賴於這個。

我想什麼做的是檢查是否.getItem.setItem需要一個回調,如果是的話,修改相應的代碼...

+2

你檢查文檔 - 如果不查看源文檔或文檔,則無法分辨。也就是說,幾乎任何異步調用都需要回調或使用promise。 –

+0

那麼我想另一種方法是嘗試確定存儲是否是localForage的一個實例?麻煩的是,這變成了一個硬編碼的邊緣情況 –

+0

你可以測試'.getItem.length'大於1.不能保證額外的參數出現在函數聲明中,但是如果是的話,它將至少爲2。 – trincot

回答

3

正如@戴夫·牛頓在評論中指出:

如果不查看源文件或文檔,無法分辨。也就是說,幾乎任何異步調用都需要回調或使用promise。

基於此,我創建了兩個函數,它們將調用打包爲.getItem.setItem並檢查它們的響應。如果他們返回無極的一個實例,它可以解決使用.then - 否則執行回調爲正常:

/** 
* Get a value from web storage regardless of whether it's sync or async 
*/ 
function getStorageItem(storage, key, callback) { 

    if (typeof callback !== 'function') throw new Error('Invalid callback handler'); 

    var result = storage.getItem(key); 

    if (result instanceof window.Promise) { 
     result.then(callback); 
    } 
    else { 
     callback(result); 
    } 
} 

/** 
* Set a value in web storage regardless of whether it's sync or async 
*/ 
function setStorageItem(storage, key, value, callback) { 

    var result = storage.setItem(key, value); 

    if (result instanceof window.Promise && callback) { 
     result.then(callback); 
    } 
    else if (callback) { 
     callback(); 
    } 
} 

這意味着我現在可以做的:

// get value from web storage 
getStorageItem(webStorage, key, function(value) { 

    if (value) { 
     // whatever I want with the value 
    } 
}); 

實施here

相關問題