![](/img/trans.png)
[英]JavaScript: Create a function groupBy that accepts an array and a callback, and returns an object
[英]Is there a way to check if a JavaScript function accepts a callback?
我試圖通過創建localForage的全局實例來將localForage支持添加到純形式 Web組件:
// 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>
在內部,pure-form執行window[self.storage]
以獲取存儲對象的句柄,並使用.getItem
, .setItem
來同步設置和檢索值。
麻煩是localForage是異步的,意味着.getItem
, .setItem
期望通過回調返回值。 因此,我目前的邏輯不起作用:
// get value from web storage
var storedContent = window[self.storage].getItem('item-key');
我意識到我可以在Promise中包裝調用,但因為它是純粹的形式不需要promises,我不想為此添加該依賴。
我想要做的是檢查.getItem
或.setItem
需要回調,如果是,請相應地修改代碼...
正如@ Dave-Newton在評論中指出:
沒有查看源或文檔就沒有辦法告訴你。 也就是說,幾乎所有異步調用都需要回調或使用promises。
基於此,我創建了兩個函數來包裝對.getItem
和.setItem
調用並檢查它們的響應。 如果他們返回Promise的實例,則使用.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
}
});
在這里實施
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.