我对Node js非常陌生,异步编程对我来说似乎很难掌握。我正在使用promise-mysql使流程同步,但我遇到了promise链中for循环的障碍
我有一个多项选择题模块。一个表存储所有的mcq问题,另一个表存储问题的所有相关选项。我使用第一个查询的输出作为第二个查询的输入,因此我承诺链接如下
var mcqAll=[]
var sql_test_q_ans='select qId, q_text from questions'
con.query(sql_test_q_ans)
.then((result)=>{
for(var i=0; i<result.length; i++)
{
ques=result[i]
var sql_test_q_ops='SELECT op_text, op_id FROM mc_ops WHERE
q_id='+result[i].q_id
con.query(sql_test_q_ops)
.then((resultOps)=>{
mcqAll.push({i: ques, ops: resultOps})
console.log(mcqAll)
})
}
})我正在尝试创建一个javascript对象数组,如下所示
[{q_text:'How many states in USA', q_ops:{1:25, 2:35, 3:45, 4:50}}
{question2 and its options}
{question3 and its options}....
]当我运行上面的代码时,对象正确地填充了所有问题的选项,但是在所有问题的所有q_text中都重复了相同的问题。
[ { q_text: 'No of states in USA',
[ {op_text: '25', mc_op_id: 113 },
{ op_text: '35', mc_op_id: 114 },
{ op_text: '45', mc_op_id: 115 },
{ op_text: '50', mc_op_id: 116}],
{ q_text: 'No of states in USA',
[ {op_text: 'A', mc_op_id: 1 },
{ op_text: 'B', mc_op_id: 2 },
{ op_text: 'C', mc_op_id: 3 },
{ op_text: 'D', mc_op_id: 4}],
{ q_text: 'No of states in USA',
[ {op_text: 'Yes', mc_op_id: 31 },
{ op_text: 'No', mc_op_id: 32 },
{ op_text: 'No sure', mc_op_id: 33 },
{ op_text: 'Might be', mc_op_id: 34}]
]我觉得这与异步流有关,因为在打印第二个查询之前,先打印console.log,然后再打印第二个查询之后的任何内容。任何洞察力都将不胜感激
编辑:为了更好地理解,我添加了一个示例输出。如输出所示,选项会更改并存储在for循环中的js对象中,但所有对象的问题都会更新到for循环中的最后一个问题
发布于 2020-03-09 15:11:26
node js当前工作的async和await,still now use to async and await,使用这个引用url:https://javascript.info/async-await
async和await是作为承诺工作,await is use to wait to execute script示例
let mcqAll=[]
let sql_test_q_ans='select qId, q_text from questions'
async function showAvatar() {
let result = await con.query(sql_test_q_ans);
if(result.length > 0){
array.forEach((async function (item, index, result) {
let q = result[index];
let sql_test_q_ops='SELECT op_text, op_id FROM mc_ops WHERE
q_id='+result[index].q_id
let executeQuery = await con.query(sql_test_q_ops);
if(executeQuery.affectedRows > 0){
mcqAll.push({index: q, ops: executeQuery})
console.log(mcqAll);
}
});
}
}https://stackoverflow.com/questions/55372992
复制相似问题