有没有办法检查JavaScript函数是否接受回调?
作者:互联网
我试图通过创建localForage的全局实例将localForage支持添加到pure-form 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>
在内部,纯格式执行window [self.storage]以获取存储对象的句柄,并使用.getItem,.setItem来同步设置和检索值.
问题是localForage是异步的,这意味着.getItem,.setItem期望通过回调返回值.因此,我当前的逻辑将不起作用:
// get value from web storage
var storedContent = window[self.storage].getItem('item-key');
我知道我可以将调用包装在Promise中,但是由于它是纯格式的,不需要promise,因此我不想为此添加依赖项.
我想做的是检查.getItem或.setItem是否需要回调,如果需要,请相应地修改代码…
解决方法:
正如@ Dave-Newton在评论中指出的那样:
there’s no way to tell without looking at the source or docs. That said, almost any async call either takes a callback or uses 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
}
});
实施here
标签:local-storage,web-component,javascript,localforage 来源: https://codeday.me/bug/20191025/1929776.html