跨模块的 indexedDB 函数 return import/export

indexedDB function return import/export across modules

我还是个初学者所以我希望这是有道理的。

我正在尝试将 return 变量从具有 IndexedDB transaction/cursor 的函数导出到另一个具有 get 事务的模块,但是该请求始终未定义。是否可以将 IndexedDB 函数的值传递给同一域中的其他模块?

db.js - 我正在导出的函数

...
function getAllData() {
    // can use getAll() however not as efficient.
    // let data = [];
    let data = [];
    let store = db.transaction("forms").objectStore("forms");
    store.openCursor().onsuccess = (event) => {
        let cursor = event.target.result;
        if (cursor) {
            console.log("FORM name is " + cursor.value.name + " and form counter is " + cursor.key);
            // data.push(cursor.value.name);
            data.push(cursor.value);
            cursor.continue();
        } else {
            console.log("All entries retrieved");
            console.log("the data form.name is " + data);
            console.log("the data is " + data.length);
            return data.length;

        }

    }

    store.openCursor().onerror = event => {
        console.log("Error in getting all data " + event.target.errorCode);
    }

};

export { getAllData } ;

a.js

import { getAlldData } from './db.js'

(() => {

function getIndex() {
    let formData = getAllData();    
    console.log("the counter is " + formData); // shows formData as undefined
}
}

)();

是否可以在a.js[=28中得到db.jsgetAllData()的return值=] 表单数据?他们 console.log 正确 db.js

我看到你通过回调让它工作了。这是使用承诺的示例。

export function getAllData() {
  return new Promise((resolve, reject) => {
    let data = [];
    let store = db.transaction("forms").objectStore("forms");

    const request = store.openCursor();
    request.onsuccess = (event) => {
      let cursor = event.target.result;
      if (cursor) {
        data.push(cursor.value);
        cursor.continue();
      } else {
         resolve(data);
      }
    };

    request.onerror = event => {
      reject(new Error('Error getting all data'));
    };
  });
}

// and then to use it in another module you do this:

import { getAllData } from 'file';

getAllData().then(data => {
  console.log('loaded %d rows', data.length);
  for (const row of data) {
    console.log('row of data:', JSON.stringify(row));
  }
}).catch(error => {
  console.log('got an error :( - ', error.message);
});