-1

I am trying to create a function that can read data from a table in websql, yet when i ran the code, i only had data in the array at alert 2.

Here is the code:

function read(table, keys){
  var data = [];
  var db = window.openDatabase("Database", "1.0", "PMM", 200000);
  db.transaction(function (tx) { 
      tx.executeSql('SELECT * FROM ' + table, [], function (tx, results) { 
            var len = results.rows.length;
            for(var i = 0; i < len; i++){
                var row = [];
                for(key of keys){
                   row.push(results.rows.item(i)[key]);
                 }
                 data.push(row);
            }
            alert(data + " --2--");
      }); 
      alert(data + "--3--");
  });
  alert("--4--")
  return data;
}

var a = read("expenses", ['name', 'cost']);
alert(a + "--1--");

i expected the alert messages to run as follows --2--, --3--, --4--, --1--

but what it did was return --4--, --1--, --3--, --2--

why?

1 Answers1

-1

I don't know what the functions you call look like, but based on your description I would believe them to be asynchronous.

Depending on their implementation, you could probably wait for their execution using .then() or another callback.

Check this out to learn more about async functions: https://javascript.info/callbacks

TemporaryName
  • 487
  • 5
  • 16