我设置了像
这样的承诺idbKeyval.set('example', 5)
.then(() => console.log('It worked!1'))
.catch(err => console.log('It failed!', err));
然后,在刷新页面之后,我想检查是否已设置并将其设置为“' 5'改变。下面是来自IDB-Keyval github的代码,但我无法从中获取价值!
idbKeyval.get('hello').then(val => console.log(val));
答案 0 :(得分:0)
您可以在https://jsbin.com/zadarebili/edit?html,output
查看使用idb-keyval
/ async
{简化语法的await
的工作示例
我无法在Stack Overflow中包含实时代码段,因为它们的嵌入工作方式,IndexedDB被阻止,但相关代码是
<body>
<button id="set">Set</button>
<button id="get">Get</button>
<p id="log"></p>
<script src="https://unpkg.com/idb-keyval@2.3.0"></script>
<script>
const KEY = 'example-key';
const VALUE = 'example-value';
function log(message) {
document.querySelector('#log').innerText = message;
}
async function get() {
return await idbKeyval.get(KEY);
}
async function set() {
await idbKeyval.set(KEY, VALUE);
}
document.querySelector('#set').addEventListener('click', async () => {
await set();
log(`Key ${KEY} was saved with value ${VALUE}.`);
});
document.querySelector('#get').addEventListener('click', async () => {
const value = await get();
log(`Key ${KEY} was read with value ${value}.`);
});
</script>
</body>