我不是一個整體具有Node.JS和Javascript的專業人員,所以請原諒我,如果這是一個愚蠢的問題。Node.JS - 在執行代碼之前等待函數完成
我正在運行一個Node.JS服務器來接受我將要運行的網站的套接字連接,並且這個腳本要做的一部分是聯繫數據庫。我有一個功能,旨在在啓動服務器之前執行此操作。但是,當我調用該函數時,它會繼續執行代碼的其餘部分,並且不會等待該函數完成。我嘗試過使用回調但無濟於事,我不知道如何使用Promise。有人可以解釋我如何解決這個問題?
這裏是我的參考代碼:
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);
但這似乎GetCompetitionDetails功能完成之前立即執行。我如何讓它們一個接一個執行?
簡單地把它回調或返回承諾... –