有没有办法来检查一个JavaScript函数是否接受回调?
问题描述:
我试图通过创建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
需要一个回调,如果是的话,修改相应的代码...
答
正如@戴夫·牛顿在评论中指出:
如果不查看源文件或文档,无法分辨。也就是说,几乎任何异步调用都需要回调或使用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
你检查文档 - 如果不查看源文档或文档,则无法分辨。也就是说,几乎任何异步调用都需要回调或使用promise。 –
那么我想另一种方法是尝试确定存储是否是localForage的一个实例?麻烦的是,这变成了一个硬编码的边缘情况 –
你可以测试'.getItem.length'大于1.不能保证额外的参数出现在函数声明中,但是如果是的话,它将至少为2。 – trincot