var result = await someFunc() returns 一个对象,但我期望对象列表

var result = await someFunc() returns an object but I expected list of object

我编写了以下用于加载 indexeddb 的函数。 (来自 IndexedDB 備忘メモ) 我认为这个函数应该是 return 对象数组。但是,有时它 return 是一个对象。 bug 的可能性有多大? Chrome 开发人员工具在 "load" 函数中表示对象类型为数组。但是,收到后 "records" 是对象类型。

    async function load(dbobj, db, index, range) {
      return new Promise(async (resolve, reject) => {
        const saves = [];
        const req = db.transaction(dbobj.storeName).objectStore(dbobj.storeName).index(index).openCursor(range);
        const onfinished = () => {
          console.log(`${saves.length} saves found.`);
          if (saves.length > 0) {
            resolve(saves[saves.length - 1]);
          }
        };
        req.onerror = reject;
        req.onsuccess = (ev) => {
          const cur = ev.target.result;
          if (cur) {
            saves.push(cur.value);
            cur.continue();
          } else {
            onfinished();
          }
        };
      });
    }

    // example of receiving data
    var records = await load(dbobj, db, index, range);

您只解析最后一个索引处的值! resolve(saves) 如果你需要整个数组;

async function load(dbobj, db, index, range) {
      return new Promise(async (resolve, reject) => {
        const saves = [];
        const req = db.transaction(dbobj.storeName).objectStore(dbobj.storeName).index(index).openCursor(range);
        const onfinished = () => {
          console.log(`${saves.length} saves found.`);
          if (saves.length > 0) {
            resolve(saves); // you are resolving only the value at the last index! resolve(saves) if you need the entire array;
          }
        };
        req.onerror = reject;
        req.onsuccess = (ev) => {
          const cur = ev.target.result;
          if (cur) {
            saves.push(cur.value);
            cur.continue();
          } else {
            onfinished();
          }
        };
      });
    }