我创建了一个类Quiz,该类扩展了Array并保存了Question对象。要创建问题对象,我需要查询sqlite数据库,因此在构造函数中包含了promise。在同一个文件中,所有这些都可以正常工作。但是,当我从另一个文件导入该类时,它仅返回一个空数组。我想我需要在实例化时使用Promise,但不确定如何执行。谁能提供任何建议?
quiz.js
var db = require("../db");
class Question {
constructor(row) {
this.question = row.question;
this.correct = row.correct;
this.answers = [row.correct, row.wrong_1, row.wrong_2, row.wrong_3];
}
}
function createQuestion(data) {
let rows = [];
data.forEach(function(row) {
rows.push(new Question(row));
});
return rows;
}
class Quiz extends Array {
constructor() {
super();
let data = this.getData("SELECT * FROM '5_1' ORDER BY RANDOM() LIMIT 1");
data.then(
function(result) {
this.push(createQuestion(result));
console.log("this " + JSON.stringify(this)); // Produces the correct output
}.bind(this)
);
} //constructor
getData(sql) {
var promise = new Promise((resolve, reject) => {
db.all(sql, (err, rows) => {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
return promise;
}
}
module.exports = Quiz;
call.js
const Quiz = require("../models/quiz.js");
var quiz= new Quiz();
console.log(quiz); // Empty array