Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/36.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 等待节点js中的sqlite3查询_Javascript_Node.js_Sqlite - Fatal编程技术网

Javascript 等待节点js中的sqlite3查询

Javascript 等待节点js中的sqlite3查询,javascript,node.js,sqlite,Javascript,Node.js,Sqlite,我正在创建一个数组JSON,其中包含一些从数据库中提取的测试名称和问题,如下所示: db.all(sql_instruction, [], (err, rows) => { if (err) { console.log(err) } rows.forEach(test=>{ let test_name = test.test_name; let question_

我正在创建一个数组JSON,其中包含一些从数据库中提取的测试名称和问题,如下所示:

db.all(sql_instruction, [], (err, rows) => {
        if (err) {
            console.log(err)
        }

        rows.forEach(test=>{
            let test_name = test.test_name;
            let question_array = [];
            sql_instruction = `SELECT * from questions where test_id = ?`;
            db.all(sql_instruction, [test.id], (err, rows) => {
                if (err) {
                    console.log(err);
                }
                rows.forEach(question=> {
                    question_array.push(question);
                });
                test_array.push(JSON.stringify({'test_name':test_name, questions:question_array}));
            });
        });
    });
如果我尝试访问第一个db.all()之外的变量“test_array”,我将得到一个空数组,因为函数的异步性质

function getAllPromise(query, params) {
    return new Promise((resolve, reject) => {

        db.all(query, params, (err, rows) => {

            if(err) {
                
                // case error
                reject(err);
            }

            // "return" the result when the action finish
            resolve(rows);
        })
    })
}

async function getTestWithQuestions() { // your code

    try {
        let sql_instruction = ""; // your SQL query;
        const rows = await getAllPromise(sql_instruction, []);
        let test_array = [];

        for(let i = 0; i < rows.length; i = i + 1) {

            const test = rows[i];
            let test_name = test.test_name;
            let question_array = [];
            sql_instruction = `SELECT * from questions where test_id = ?`;

            const question_rows = await getAllPromise(sql_instruction, [test.id]);
            question_rows.forEach(question=> {
                question_array.push(question);
            });

            test_array.push(JSON.stringify({'test_name':test_name, questions:question_array}))
        }

        return test_array;

    } catch(error) {
        console.log(error);
        throw error;
    }
}

// using
// you need to add the keyword "async" in the function that call getTestWithQuestions, then :

const testWithQuestions = await  getTestWithQuestions(); // testWithQuetions is `test_array`

// if you don't want to add async keyword, then : 
getTestWithQuestions()
.then(testWithQuestions => console.log(testWithQuestions))
.catch(error => console.log(error));

“等待”完成“test_array”变量以在应用程序中进一步使用它的最佳方式是什么?

我们可以使用Promise和async/await sugar语法使异步代码看起来像同步代码。在下面的代码中,我创建了一个函数
getAllPromise
,将
db.all
方法包装在Promise中。然后我可以“等待”我的
getAllPromise
函数

function getAllPromise(query, params) {
    return new Promise((resolve, reject) => {

        db.all(query, params, (err, rows) => {

            if(err) {
                
                // case error
                reject(err);
            }

            // "return" the result when the action finish
            resolve(rows);
        })
    })
}

async function getTestWithQuestions() { // your code

    try {
        let sql_instruction = ""; // your SQL query;
        const rows = await getAllPromise(sql_instruction, []);
        let test_array = [];

        for(let i = 0; i < rows.length; i = i + 1) {

            const test = rows[i];
            let test_name = test.test_name;
            let question_array = [];
            sql_instruction = `SELECT * from questions where test_id = ?`;

            const question_rows = await getAllPromise(sql_instruction, [test.id]);
            question_rows.forEach(question=> {
                question_array.push(question);
            });

            test_array.push(JSON.stringify({'test_name':test_name, questions:question_array}))
        }

        return test_array;

    } catch(error) {
        console.log(error);
        throw error;
    }
}

// using
// you need to add the keyword "async" in the function that call getTestWithQuestions, then :

const testWithQuestions = await  getTestWithQuestions(); // testWithQuetions is `test_array`

// if you don't want to add async keyword, then : 
getTestWithQuestions()
.then(testWithQuestions => console.log(testWithQuestions))
.catch(error => console.log(error));
函数getAllPromise(查询,参数){ 返回新承诺((解决、拒绝)=>{ db.all(查询,参数,(错误,行)=>{ 如果(错误){ //案例错误 拒绝(错误); } //“返回”操作完成时的结果 解析(行); }) }) } 异步函数getTestWithQuestions(){//您的代码 试一试{ 让sql_指令=”;//您的sql查询; const rows=等待getAllPromise(sql_指令,[]); 让测试_数组=[]; for(设i=0;i{ 问题\数组推送(问题); }); test_array.push(JSON.stringify({'test_name':test_name,questions:question_array})) } 返回测试单元阵列; }捕获(错误){ console.log(错误); 投掷误差; } } //使用 //您需要在调用getTestWithQuestions的函数中添加关键字“async”,然后: const testWithQuestions=等待getTestWithQuestions();//testWithQuetions是“测试数组”` //如果不想添加async关键字,则: getTestWithQuestions() .then(testWithQuestions=>console.log(testWithQuestions)) .catch(错误=>console.log(错误)); 您可以找到有关回调、承诺和异步/等待的更多信息