IndexedDB 从IDB-Keyval获取值并将其赋值给变量

ubbxdtey  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(1)|浏览(179)

我设定了一个承诺

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));
sd2nnvve

sd2nnvve1#

您可以在https://jsbin.com/zadarebili/edit?html,output中看到使用async/await(这简化了语法)使用idb-keyval的工作示例
我不能在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>

相关问题