我想查詢數據庫中,我對工作項目的快速和MySQL服務器響應用於教學和培訓用戶。我有根據用戶(例如醫生)的兩個型諾言,一個詢問的問題(和它們的question_ids)的數據庫,然後接下來的查詢需要的questions_ids,並選擇相應的答案和answer_ids的問題。代碼如下所示:不發送所有需要的數據
var express = require('express');
var mysql = require('mysql');
var path = require('path');
var async = require('async')
var app = express();
var connection = mysql.createConnection({
host: "localhost",
user: "root",
password: "123456",
database: "myDB"
})
app.set('port', 3001);
var questions = [];
var question_ids = [];
var answers = [];
var answer_ids = []
app.get('/training/:user_type', function (req, res) {
var user_type = req.params.user_type // gets the value for the named parameter user_id from the url
var sql_command_1 = "SELECT * FROM questions WHERE type = ?"
var sql_command_2 = "SELECT * FROM answers WHERE question_id = ?"
function getQuestions() {
return new Promise((resolve, reject) => {
connection.query(sql_command_1, user_type, function (error, results) {
for (i = 0; i < results.length; i++) {
questions.push(results[i].question_text);
question_ids.push(results[i].question_id);
}
resolve({questions: questions, question_ids: question_ids});
})
})
}
function getAnswers(question_ids) {
console.log(question_ids)
return new Promise((resolve, reject) => {
for (i = 0; i < question_ids.length; i++) {
connection.query(sql_command_2, question_ids[i], function (error, results) {
for (i = 0; i < results.length; i++) {
answers.push(results[i].answer_text);
answer_ids.push(results[i].answer_id);
}
console.log(answers);
console.log(answer_ids);
resolve({answers: answers, answer_ids: answer_ids});
});
}
});
}
getQuestions().then((result) => {
console.log(result);
return getAnswers(result.question_ids);
}).then((result) => {
res.json({"Type": user_type, "Questions": questions, "Answers": answers});
});
});
app.listen(app.get('port'));
我預期的響應是醫生爲USER_TYPE,對於「問題」等8個答案在「答案」兩個不同的問題(四個答案爲每個不同的問題)。不過,我只得到了第一個問題,不是四個第二的四個答案。我看過了代碼,看着異步執行,但似乎無法找到我的問題。
@codtex是對的,他們的代碼更加高效:) –
作爲一名程序員,您自己找到了解決方案,這是一個非常好的信號。我只是想把你的想法指向另一個更高效的方法,我很高興你明白它的工作原理:)幹得好! – codtex