Skip to content Skip to sidebar Skip to footer

How To Return Indexeddb Query Result Out Of Event Handler?

I have to return query result from indexedDB, but the result is only available in onsuccess event handler. 1 function listPeople(){ ... 4 var open = indexedDB.open('Accord

Solution 1:

you can either use this project: https://github.com/jakearchibald/idb

or you need to wrap indexedDB operation into a promise and thus make the list people asynchronous:

functionlistPeople() {
// ...returnnewPromise(function (resolve, reject) {
    var open = indexedDB.open("AccordionDatabase",1),
    open.onsuccess = function() {
      var db = open.result;
      var transaction = db.transaction("PeopleStore", "readwrite");
      var store = transaction.objectStore("PeopleStore");
      var request = store.getAll();
      request.onsuccess = function(event){
        resolve(event.target.result);
      };

      request.onerror = function(event) { reject(event) }

      // Close the db when the transaction is done
      transaction.oncomplete = function() {
        db.close();
      };
      transaction.onerror = function(event) { reject(event) }
    };
    open.onerror = function(event) { reject(event) }
  })
}

// usage:functiondoWorkWithListedPeople(people) {
  // ...
}

functionhandleErrorsDuringIndexedDbRequest(event) {
  // ...
}

listPeople().then(doWorkWithListedPeople).catch(handleErrorsDuringIndexedDbRequest)

// or alsolistPeople().then(function(people) { doWorkWithListedPeople(people) })

The thing is, you create a promise that represents work that will be eventually done. You can tell JS that eventually, when the promise has been resolved (success), you want to then to work with anything that has been passed to resolve. See https://developer.mozilla.org/cs/docs/Web/JavaScript/Reference/Global_Objects/Promise and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function for details


EDIT

furthermore, if you don't like thens, you can make do with async await, which unwraps promises. Just beware, you can only use await keyword from within async function:

async function doStuff() {
  try {
    var people = await listPeople()
    // now you can work with ppl
  }
  catch (err) {
    // handle listPeople errors here
  }
}

Solution 2:

indexedDB functions are nearly all asynchronous. You should be familiar with writing asynchronous Javascript before using indexedDB.

Post a Comment for "How To Return Indexeddb Query Result Out Of Event Handler?"