我正在尝试从func change(a interface{}) {
rv := reflect.ValueOf(a)
changerv(rv)
}
func changerv(rv reflect.Value) {
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() == reflect.Struct {
changeStruct(rv)
}
if rv.Kind() == reflect.Slice {
changeSlice(rv)
}
}
// assumes rv is a slice
func changeSlice(rv reflect.Value) {
ln := rv.Len()
if ln == 0 && rv.CanAddr() {
var elem reflect.Value
typ := rv.Type().Elem()
if typ.Kind() == reflect.Ptr {
elem = reflect.New(typ.Elem())
}
if typ.Kind() == reflect.Struct {
elem = reflect.New(typ).Elem()
}
rv.Set(reflect.Append(rv, elem))
}
ln = rv.Len()
for i := 0; i < ln; i++ {
changerv(rv.Index(i))
}
}
// assumes rv is a struct
func changeStruct(rv reflect.Value) {
if !rv.CanAddr() {
return
}
for i := 0; i < rv.NumField(); i++ {
field := rv.Field(i)
switch field.Kind() {
case reflect.String:
field.SetString("fred")
case reflect.Int:
field.SetInt(54)
default:
fmt.Println("unknown field")
}
}
}
保存数组中的数据,但是每次我得到空数组时,我都不明白它是范围内的还是方法db.get(...) => {...}
?请帮我解决这个问题。我的主要目标
db.get(...) => {...}
我想做的是获取const sqlite3 = require('sqlite3');
let db = new sqlite3.Database('./ProblemsForPatan.db', sqlite3.OPEN_READONLY);
let sql = 'SELECT * FROM Problems';
db.all(sql, [], (err, rows) => {
rows.forEach((rowQuestion) => {
let arrayWithQuestionsId = _.split(rowQuestion.problem_questions_id, ',')
var arrayOfAnswers = []
arrayWithQuestionsId.forEach((id) => {
let sql = `SELECT * FROM QuestionsAndAnswersOfProblems WHERE question_id = ?`
db.get(sql, [id], (err, rowAnswer) => {
console.log(rowAnswer) // Object
arrayOfAnswers.push(rowAnswer)
}) // db.get(...)
console.log(arrayOfAnswers) // []
}) // arrayWithQuestionsId.forEach(...)
rowQuestion.answer = arrayOfAsnwers;
}) // rows.forEach(...)
console.log(rows) // [objects with 'answer': []]
}) // db.all(...)
个对象并添加rowQuestion
字段而不是answer: [array of objects]
rowQuestion
答案 0 :(得分:1)
您拨打db.get()
以获取答案是异步的,这意味着您的console.log(rows)
在填充答案之前正在执行。当“行”处理完毕后,您将需要使用回调。
db.all(sql, [], (err, rows) => {
// track the index here with a second parameter of "index"
rows.forEach((row, index) => {
// loop over the problem_questions_id
_.split(row.problem_questions_id, ',').forEach((id) => {
let sql = `SELECT * FROM QuestionsAndAnswersOfProblems WHERE question_id = ?`;
// use db.all not db.get to fetch an array of answers
// this call is asynchronous so we need to check if we are done inside the callback
db.all(sql, [id], (err, answers) => {
// "answers" is an array here
row.answer = answers;
// if the index is one less than the length it's the last
if (index === rows.length-1) {
// we're done!
done(rows);
}
});
});
});
});
// this is called asynchronously when all the answers have been fetched
function done(rows) {
console.log(rows);
}