IndexedDB 为什么在indexDB返回请求的值之前,这个函数中的返回发生了?

v6ylcynt  于 2022-12-09  发布在  IndexedDB
关注(0)|答案(2)|浏览(145)

我有一个非常基本的indexedDB,只有一个键。我想检索这个值来执行一个操作。不幸的是,应该执行这个操作的函数在indexedDB返回值之前返回了undefined
函数如下:

const getValue = async () => {
   const res = await IndexedDB.get(1)
   return console.log("res", res) // displayed before "res" has finished
};
  

export default class IndexedDB {
  static createDB() {
    const request = indexedDB.open("myApp", 1);
    request.onupgradeneeded = (e) => {
      const db = e.target.result;
      return db.createObjectStore("myData", { autoIncrement: true });
    };
  }

  static addData(data) {
    const db = indexedDB.open("myApp", 1);
    db.onsuccess = (e) => {
      const request = e.target.result
        .transaction(["myData"], "readwrite")
        .objectStore("myData")
        .add(data);
      request.onsuccess = (res) => res.target.result;
      request.onerror = (err) => err
    };
  }

  static get(key) {
    const db = indexedDB.open("myApp", key);
    db.onsuccess = (e) => {
      const request = e.target.result
        .transaction(["myData"])
        .objectStore("myData")
        .get(key);
      request.onsuccess = (res) => res.target.result;
      request.onerror = (err) => err
    };
  }

}

如何解决这个问题?

6l7fqoea

6l7fqoea1#

您的IndexedDb.get函数不是异步的,但您正在等待它是出于某种原因?
将其更改为:

static get(key) {
  return new Promise((resolve, reject) => {
    const db = indexedDB.open("myApp", key);
    db.onsuccess = (e) => {
      const request = e.target.result
        .transaction(["myData"])
        .objectStore("myData")
        .get(key);
      request.onsuccess = (res) => resolve(res.target.result);
      request.onerror = (err) => reject(err);
    };
  });
}
ki0zmccv

ki0zmccv2#

IndexedDb.get有一些异步操作indexedDB.open("myApp", key)。要处理这种同步函数,您需要使用promise或回调函数。
使用承诺

static get(key) {
    let resolve, reject;
    const promise = new Promise((re, rj) => { resolve = re; reject = rj; }),
        db = indexedDB.open("myApp", key);
    db.onsuccess = (e) => {
      const request = e.target.result
        .transaction(["myData"])
        .objectStore("myData")
        .get(key);
      request.onsuccess = (res) => resolve(res.target.result);
      request.onerror = (err) => reject(err);
    };
    return promise;
}

使用回调

static get(key, successCB, errorCB) {
    db.onsuccess = (e) => {
      const request = e.target.result
        .transaction(["myData"])
        .objectStore("myData")
        .get(key);
      request.onsuccess = successCB;
      request.onerror = errorCB;
    };
}
// get(key, (res) => {}, (err) => {})

相关问题