search

Home  >  Q&A  >  body text

Solve the callback hell problem when exporting a value in SQL query

<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粉014218124P粉014218124450 days ago462

reply all(1)I'll reply

  • P粉545218185

    P粉5452181852023-09-05 18:56:24

    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
    }

    reply
    0
  • Cancelreply