Really sorry if this has been asked a hundred times, but I haven't been able to adapt any previous SO solutions I found to my problem. A lot of them were Ajax specific.
I'm new to asynchronous callbacks with Node, and as such I'm having an issue with properly 'returning' data from an asynchronous callback. In my example, I'm trying to return CharList
. The SQL queries and the data are all valid, so those aren't too important.
I've tried simply returning the values, which I quickly learned is impossible and defeats the purpose of asynchronous callbacks.
EDIT: I've also tried defining CharList
outside of the function and then assigning the values through the function, but logging CharList
after the function has finished prints an empty array.
// index.js
const sql = require('./sql')
const query = require('./queries');
function AllCharsToArray() {
query.character.GetAllChars(function(result) {
let CharList = [];
for (var i in result) {
CharList.push(result[i]._Name)
}
})
}
/*
{
"characters":
[
{"_Name":"Charname 1"},
{"_Name":"Charname 2"},
{"_Name":"Charname 3"}
]
}
*/
// queries.js
const mysql = require('mysql');
const sql = require('./sql')
function GetAllChars(callback) {
sql.conn.query(`SELECT _Name FROM characters;`, function(error, results, fields) {
return callback(results); // returns RowDataPacket
})
}
exports.character = {
GetAllChars: GetAllChars,
}
Ultimately, I'm trying to get CharList
to be available outside of AllCharsToArray
so I can export them to an express.js route.