Home > Blockchain >  get webpacked module function variable
get webpacked module function variable

Time:12-17

So, i have a function in file that converts into bundler.js via webpack (devtool: 'eval-source-map'):

function getTable(tname, trowid) {
  return get(ref(db, `table_name/${tname}/table_row_${String("0"   trowid).slice(-2)}`)).then((snapshot) => {
    if (snapshot.exists()) {
      console.log(snapshot.val()); // need to return this value
    }
  });
}
window.getTable = getTable;

and i need call this function in main.js smt like this:

for (i = 0; i < 69; i  ) {
  document.getElementById(i).value = window.getTable(tname, i);
}

I'd tried simply return this vale, do it global variable and more, but in result i'm still getting "undefined".

CodePudding user response:

Instead of logging your value, return it to the Promise your getTable() function is returning with return snapshot.val() :

if (snapshot.exists()) {
  return snapshot.val();
}

This makes it so getTable() returns a Promise that fulfills with the value that snapshot.val() returns. Now you have a few options. One is to use async/await on each promise returned by the getTable() function to "extract" the value from the Promise:

async function populateValues() {
  for (let i = 0; i < 69; i  ) {
    document.getElementById(i).value = await getTable(tname, i);
  }
}
populateValues();

This will call each getTable function one at a time, perform the asynchronous operation/code within it, wait for that to complete (ie: wait for the Promise getTable() returns to fulfill with a value), then update your element's .value. Once done, it will proceed to the next iteration, and it will do this 69 times. For something faster, you can kick off all your calls to getTable() in parallel, and then use Promise.all() to wait until all of them have been fulfilled:

async function populateValues() {
  const promises = [];
  for (let i = 0; i < 69; i  ) {
    promises.push(getTable(tname, i)); // kick off all your asynchronous calls (so that they run in parallel)
  }

  const tableValues = await Promise.all(promises); // wait for each async operation to finish, then iterate the data and update your UI
  for(const [i, val] of tableValuese.entries()) { // you can use a standard `for` loop here to iterate your `tableValues` array if you'd like
    document.getElementById(i).value = val;
  }
   
}
populateValues();
  • Related