简体   繁体   中英

How to store SQL query result in a JavaScript variable to use in global scope?

Beginner here, I'm trying to store the result of a SQL query into a JavaScript variable so I'd be able to access it from the global scope to use in other code.

Here's the code:

const latestRunContacts = () => {
  db.all(
    `SELECT email FROM Contacts_tbl WHERE RunID = (SELECT MAX(UID) FROM Run_tbl)`,
    (err, row) => {
      console.log(row);
    }
  );
};

This logs the the values I'm trying to get, but as soon as I try to do this:

const latestRunContacts = () => {
  db.all(
    `SELECT email FROM Contacts_tbl WHERE RunID = (SELECT MAX(UID) FROM Run_tbl)`,
    (err, row) => {
      return row;
    }
  );
};

console.log(latestRunContacts());

Then it returns undefined... Since typeof row is an object, I've tried declaring an object and assigning the result of the SQL query to it and calling the function immediately like so:

let contactEmail = {
  email: (function latestRunContacts() {
    db.all(`SELECT email FROM Contacts_tbl WHERE UID = '1'`, (err, row) => {
      return row;
    });
  })(),
};

console.log(contactEmail.email);

But this also just returns undefined.

Is what I'm trying to do even possible? If so, how??

I missed the fact that the query returns an array of objects like below:

[
   {
      email: "email@address.xyz"
   }
]

To store the results in a variable it'll have to be assigned to the index of the object in the array like so:

let results = "";

const latestRunContacts = () => {
  db.all(
    `SELECT email FROM Contacts_tbl WHERE RunID = (SELECT MAX(UID) FROM Run_tbl)`,
    (err, row) => {
      results = row[0].email;
    }
  );
};

Running console.log(results) would then log the string email@address.xyz

This is related to callbacks and to the asynchronous nature of javascript.

A quick fix for your problem would be this:

let latestContacts;
db.all(
  `SELECT email FROM Contacts_tbl WHERE RunID = (SELECT MAX(UID) FROM Run_tbl)`,
  (err, rows) => {
    if (err) throw err;
    latestContacts = rows;
    console.log(latestContacts);
  },
);

I recommend reading this article, summarizing callbacks, promises and async functions: https://scotch.io/courses/10-need-to-know-javascript-concepts/callbacks-promises-and-async

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM