gpt4 book ai didi

javascript - 如何正确解决此 knex.js promise ?

转载 作者:行者123 更新时间:2023-12-03 00:47:24 25 4
gpt4 key购买 nike

我正在使用 knex,这是我在从数据库请求后获取 Question_info 对象的代码。

let question_info = knex.select('id', 'question', 'pre_question', 'response_options_id').from('_questions').whereNot({'progress': 100}).andWhere({'school_id': school_id}).orderBy('date_created', 'asc')
.map((question) => {
//going through all possible questions
helpers.debug("Question", question);
//checking if there are responses
return knex('_responses').where({'question_id': question.id, 'student_id': event.user.id}).first()
.then((response) => {
//if no responses, return question_info object
if(!response){
return knex.select('options_json').from('_response_options').where({'id': question.response_options_id}).first()
.then((options) => {
return {
question_id: question.id,
question: question.question,
pre_question: question.pre_question,
response_options: JSON.parse(options.options_json)
}
});
}
});
}).catch((e) => {
console.error('Error', e);
});

当第一个问题已经得到解答时,我的返回值显示为空。如何正确使用 knex 获得不带 null 的返回数组。

[
null,
{
"question_id": "2",
"question": "What is second question?",
"pre_question": "Hey!!",
"response_options": [
{
"title": "Yes",
"value": "Yes"
},
{
"title": "Maybe",
"value": "Maybe"
},
{
"title": "No",
"value": "No"
}
]
},
{
"question_id": "3",
"question": "Third Question?",
"pre_question": "Yo",
"response_options": [
{
"title": "Yes",
"value": "Yes"
},
{
"title": "Maybe",
"value": "Maybe"
},
{
"title": "No",
"value": "No"
}
]
}
]

最佳答案

看起来您的问题是,如果第二个查询确实返回了响应,那么您不会返回任何内容。

// this part of your code seems to be wrong
if (!response) {
// return choices because there was no response found
return knex('choices')...
}

应该是这样的:

// this part of your code seems to be wrong
if (!response) {
// return choices because there was no response found
return knex('choices')...
} else {
return response;
}

编辑这或多或少是如何使用单个查询和连接做同样的事情(我没有测试这个,所以它可能不起作用,但它应该给出如何实现它的一般概念):

let question_info = knex('_questions as q')
.select(
'id',
'question',
'pre_question',
'response_options_id',
'r.id as r_id',
'options_json'
)
.join('_responses as r', builder => {
builder
.on('q.id', 'r.question_id')
.onVal('r.student_id', event.user.id);
})
.join('_response_options as ro', 'q.response_options_id', 'ro.id')
.where('q.school_id', school_id)
.whereNot('q.progress', 100)
.whereNull('r.id')
.orderBy('q.date_created', 'asc')
.map(notAnsweredQuestion => {
return {
question_id: notAnsweredQuestion.id,
question: notAnsweredQuestion.question,
pre_question: notAnsweredQuestion.pre_question,
response_options: JSON.parse(notAnsweredQuestion.options_json)
};
}).catch((e) => {
console.error('Error', e);
});

关于javascript - 如何正确解决此 knex.js promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53185587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com