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??
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
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments