Solve the callback hell problem when exporting a value in SQL query
P粉014218124
2023-09-04 21:09:38
<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>
Thanks to Fredrik, I fixed it. I ended up using the following promise