Solve the callback hell problem when exporting a value in SQL query
P粉014218124
P粉014218124 2023-09-04 21:09:38
0
1
464
<p>My goal is to set <code>someVar</code> to 1 if my SQL query finds a result. The problem is, the assignment is local, and when I try to use <code>console.log(someVar)</code>, the result is 1 inside the block, but 0 outside the block. Is there a way to export the values ​​outside the block? </p> <pre class="brush:js;toolbar:false;">let someVar = 0; con.query(`SOME SQL QUERY`, (error, rows) => { if (error) throw error if (rows.length > 0) { someVar = 1; //console.log(someVar) -> The result is 1 } }); con.end(); //console.log(someVar) -> The result is 0 if (someVar === 0) { //Some code } </pre></p>
P粉014218124
P粉014218124

reply all(1)
P粉545218185

Thanks to Fredrik, I fixed it. I ended up using the following promise

let promiseQuery = await new Promise((resolve, reject) => {
    con.query(`SOME SQL QUERY`, (error, results, fields) => {
        if (error) reject(error);
        resolve(results || {});
    })

})
const someVar = promiseQuery.length
if (someVar === 0) {
    // Some code
} else {
    // Some code
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template