0

I have a function that retrieves data from an indexedDB:

function dbGetProdData() {
   return new Promise((resolve)=>{
    if (!indexedDBAvailable) {
      getDataByFetch();
      createSizeFilterOptions();
      resolve(false);
    }
    tprodArr=[];
    tcurrentProdArr=[];
    console.log(`gettingData: `,currentProdArr.length); //<==this is firing well after the .then() when the function is called.
      let requestNew = indexedDB.open(dbName, dbVersion);
      requestNew.onupgradeneeded = (event) => {
        db = event.target.result;
        const objectStore = db.createObjectStore("currentCollection", { keyPath: "id" });
      };
      requestNew.onsuccess= (event) => {
        console.log(`db success`)  //this is firing well after the .then()
        db=event.target.result;
        currentCollectionStore = db.transaction("currentCollection", "readwrite").objectStore("currentCollection");
        currentCollectionStore.get(1).onsuccess = async (event) => {
          console.log(`retrieving: `,prodArr.length);
          if (event.target.result.prodArr.length>0) {
            tprodArr=event.target.result.prodArr;
          }
          if (event.target.result.currentProdArr.length>0) {
            tcurrentProdArr=event.target.result.currentProdArr;
          }
          console.log(`is valid: `,pagesInCollection,tprodArr.length/paginationIndex)
          if (+pagesInCollection-1>=+tprodArr.length/paginationIndex) {
           await getDataByFetch();       
          } else {
            console.log(`got current data`); //this is firing well after the .then()
            prodArr=tprodArr;
            currentProdArr=tcurrentProdArr;
            console.log(`prodArr: `,tprodArr.length)
            tprodArr=null;
            tcurrentProdArr=null;
          }
        };
      }
     requestNew.oncomplete=function() {
       resolve(true);
     }
   });
 }

The issue is I need to wait for the results before the rest of the javascript continues.

I'm calling it like this:

dbGetProdData().then(function() {createSizeFilterOptions()});

How do I call it so that execution pauses until the indexedDB functions are complete? I can't use await because of where I'm calling this. I'm not in an async function.

Chris
  • 650
  • 7
  • 20
  • You should either use Promise.then or await. There is no other waiting for async calls in javascript. ```dbGetProdData().then(() => { // dbGetProdData should be completed here });``` – Svetoslav Petkov Sep 27 '22 at 15:09
  • Yeah. As I said, I can't use await. As my code show, I'm already doing what you suggest. – Chris Sep 27 '22 at 16:11
  • If we assume the dbGetProdData is working fine, it returns a Promise of boolean and you want to do something after this. I have prepared a code sample for you. Modify it so that you can illustrate what is wrong. https://stackblitz.com/edit/react-ruleo2?file=src/App.js – Svetoslav Petkov Sep 27 '22 at 16:24
  • your example is not doing anything that take any time in getProdData(). Of course it will work. Do something promisy, like indexedDB data retrieval. See where I have console.log(`db success`)? That fires well after the .then() when I call the function. – Chris Sep 27 '22 at 16:38
  • I indicated in the original question places where something is firing after the .then() when I call the function. – Chris Sep 27 '22 at 16:43
  • That's how async works. Things happen `a` (out of) `sync` (together in time). Not sure what you're looking for; there's no way to do something that's async synchronously. Call the remainder of your code you wish to occur after `dbGetProdData` executes within the function passed to `then`. Period. That's it. No silver bullets. No get-out-of-jail-free cards. – Heretic Monkey Sep 27 '22 at 16:47
  • Are you sure the ```if (!indexedDBAvailable) resolve(false);``` is not called. (Which resolves the promise and calls the then). You do not stop the function execution after the resolve(false); put a console.log before the resolve(false); – Svetoslav Petkov Sep 27 '22 at 17:02
  • Yes. Only true is being returned. @Heritic, I've also done that, waiting for the promise to resolve. The rest of the code depends on retrieving data from the function. The promise is resolving but the function is not complete. No data is loaded until seconds after the promise is resolved. – Chris Sep 27 '22 at 17:06
  • I get it now ! The requestNew.oncomplete=function() { resolve(true); } si called way before. requestNew.onsuccess – Svetoslav Petkov Sep 27 '22 at 17:08
  • I managed to create a minimum reproducible example mocking the data fetching. But it shows that your code as you wrote it is here. I spend some time to mock all shaky variables. Please fork and modify it to prove your issue. I hae added two ```resolve(true)``` otherwise the promise never got resolved https://stackblitz.com/edit/react-qyuxgr?file=src/index.js – Svetoslav Petkov Sep 27 '22 at 17:45

0 Answers0