简体   繁体   中英

SQL and Node: How can I run three different query and return the result one by one

I have total of 3 SQL query. I have done my connection with database through node.js. How can I write a function that helps me to run all the 3 query one by one and return the result as json to angular front end.

This is the code that I have. Is there any better way to make a call to the query as return then one by one. I am using the post method for the api.

    var sqlquery=" " 
    var sqlsecond=" "
    var sqlthird=" "

    mysqlConnection.query(sqlquery,(err,result)=>{
    if(err){
        console.log("Error"+err);
     }
    else{
        return response.json(result);

    }
    selectquery2(sqlsecond)
    selectquery3(sqlthird)

    })

})
function selectquery2(sqlquery1){
mysqlConnection.query(sqlquery1,(err,result1)=>{
    if(err){
        console.log("Error"+err);
     }
    else{
        return response.json(result1);

    }
})
}
function selectquery3(sqlquery2){
mysqlConnection.query(sqlquery2,(err,result2)=>{
    if(err){
        console.log("Error"+err);
     }
    else{
        return response.json(result2);

    }
})
}

You can use Promise and ready all 3 results then return all of them together in json format. For example

router.get('/', async function(req, response){
    try{
        var sqlquery=" " 
        var sqlsecond=" "
        var sqlthird=" "

        let result1 = await selectquery(sqlquery)

        let result2 = await selectquery(sqlsecond)

        let result3 = await selectquery(sqlthird)

        return response.json({result1:result1, result2:result2, result3:result3});

    }
    catch(err){
        response.status(500).end();
    }
})


async function selectquery(sqlquery){
    return new Promise((resolve, reject) => {
        mysqlConnection.query(sqlquery,(err,result)=>{
            if(err){
                reject(err);
            }
            else{
                resolve(result);
            }
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM