0

I have a series of functions being called following a .then() and a $(document).ready(function(){ that adds values to the object and then uses them to load further parts of the page. I have them in the proper order they should be running but when the function gets called it runs the later functions before the first function has finished filling out the object

main.js :

profileData.getProfile()
  .then(() => {
    $(document).ready(function() {
      profileData.queryPermissionsId();
      loadNav();

      console.log(profileData.pfData);
      console.log(profileData.pfData.is_admin);

      profileData.testAccount();
      //create web page elements
    });
  })

profileData.js:

function queryPermissionsId() {
  let x;
  console.log("SELECT id FROM `accounts` WHERE email = '" + pfData.email + "'");
  $query = "SELECT id FROM `accounts` WHERE email = '" + pfData.email + "'";
  connection.query($query, function(err, result, fields) {

    if (err) {
      console.log(err);
    }
    console.log(result);
    x = result[0].id;
    $query = "SELECT * FROM `permissions` WHERE accountId = '" + x + "'";
    connection.query($query, function(err, result, fields) {
      if (err) {
        console.log(err);
      }
      console.log(result[0]);

      pfData.accountId = result[0].accountId;
      pfData.can_see_inventory = result[0].can_see_inventory;
      pfData.can_see_employees = result[0].can_see_employees;
      pfData.can_see_past_orders = result[0].can_see_past_orders;
      pfData.can_see_open_orders = result[0].can_see_open_orders;
      pfData.can_create_order = result[0].can_create_order;
      pfData.can_change_privialages = result[0].can_change_privialages;
      pfData.can_create_inventory_items = result[0].can_create_inventory_items;
      pfData.can_create_inventory_categories =
        result[0].can_create_inventory_categories;
      pfData.is_admin = result[0].is_admin;

      console.log(pfData);
    });
  });
}

The console returns it in this order:

pfData { (All parts of object filled with permissions being undefined) }

undefined (from console.log(profileData.pfData.is_admin) in main.js

[RowDataPacket] (from first query in queryPermissionsId())

Account in db  (from testAccount())

[RowDataPacket] (from 2nd query in queryPermissionsId() which should have run immediately after the first query)

pfData { (All parts of object filled with permissions and user data) }

I have no idea why it runs the rest of the functions in main.js before completing the object, any help would be greatly appreciated

Apologies is my explanation is messy

Barmar
  • 741,623
  • 53
  • 500
  • 612

0 Answers0