I am not a professional with Node.JS and Javascript as a whole, so please forgive me if this is a stupid question.
I am running a Node.JS server to accept socket connections for a website that I will be running, and part of what this script is meant to do is contact a database. I have a function that is designed to do this before starting the server. However, when I call the function it continues with the rest of the code anyway and does not wait for the function to finish. I have tried using callbacks but to no avail, and I have no clue how to use Promises. Can someone explain how I resolve this issue?
Here is my code for reference:
function GetCompetitionInfo(competitionID,callback){
var competitionInfo = {
id:competitionID,
title:"",
topic:"",
difficulty:"",
description:"",
jackpot:0,
answer:0,
author:0
}
var testVariable;
sqlConnection_read.connect(function(err){
if(err) throw err;
console.log("Connected to TSDB, retrieving competition info...");
var query = "SELECT * FROM competitions WHERE PuzzleID="+competitionID+";";
sqlConnection_read.query(query,function(err,result){
if(err) {console.log("Uh oh spaghettiohs");throw err;}
competitionInfo.title = result[0].Puzzle_Title;
competitionInfo.topic = result[0].Puzzle_Topic;
competitionInfo.difficulty = result[0].Puzzle_Difficulty;
competitionInfo.description=result[0].puzzle_description;
competitionInfo.answer=result[0].Puzzle_Answer;
competitionInfo.jackpot=result[0].Puzzle_Jackpot;
competitionInfo.author=result[0].Puzzle_Author;
callback(competitionInfo);
});
});
}
GetCompetitionInfo(0,function(data){
competitionInfo=data;//This is a variable outside of the scope
});
//I want this to be executed afterwards
var competitionTitle = competitionInfo.title;
var competitionTopic = competitionInfo.topic;
var competitionDifficulty = competitionInfo.difficulty;
var competitionDescription = competitionInfo.description;
var competitionAnswer = competitionInfo.answer;
var jackPotTotal = competitionInfo.jackpot;
var competitionAuthor = competitionInfo.author;
console.log("Title:"+competitionTitle);
console.log("Topic:"+competitionTopic);
console.log("Difficulty:"+competitionDifficulty);
console.log("Description:"+competitionDescription);
console.log("Answer:"+competitionAnswer);
console.log("Jackpot:"+jackPotTotal);
console.log("Author UID:"+competitionAuthor);
But this seems to immediately execute before the GetCompetitionDetails function has finished. How do I make them execute one after the other?