Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js wait("await") for SQL database query before proceeding

I have spent a lot of time reading up on this but I simply don’t get how to solve it.

I have an application that uses a token that is stored in a SQL database. I need that token before the application can proceed.

I’m trying to solve it with "await" but it doesn’t work. The SQL query result is still retrieved "too late".

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const pool = mysql.createPool({
    user        : 'xxxx', // e.g. 'my-db-user'
    password    : "xxxx", // e.g. 'my-db-password'
    database    : "xxxx", // e.g. 'my-database'
    // If connecting via localhost, specify the ip
    host        : "xxxx"
    // If connecting via unix domain socket, specify the path
    //socketPath  : `/cloudsql/xxxx`,
});   

const isAuthorized = async (userId) => {
    
      let  query = "SELECT * FROM auth WHERE id = 2";
    
      
      await pool.query(query, (error,results) => {
        if (!results[0]) {
           console.log("No results");
           return
          } else {
            tokenyay=results[0].refreshtoken;
            console.log("results: "+results[0].refreshtoken);
            return results[0].refreshtoken;
            
          }
        });
      
    
      await console.log("tokenyay: "+tokenyay);
      
      if (tokenyay != null && tokenyay != '') {
      refreshTokenStore[userId] = tokenyay;
      }
    
      console.log(userId);
      console.log(refreshTokenStore[userId] ? true : false);
    
      return refreshTokenStore[userId] ? true : false;
    };

>Solution :

I don’t know what your pool is, but judging from the callback, we can see that pool.query() method is not await-able.

You can manually create a Promise for it, though, which is await-able, for example

await new Promise((resolve, reject) => {
    pool.query(query, (error, results) => {
        if (error) reject(error);

        if (!results[0]) {
            console.log("No results");
            resolve(); // give `undefined` to the `await...` and make it stop waiting
            return;
        } else {
            tokenyay = results[0].refreshtoken;
            console.log("results: " + results[0].refreshtoken);
            resolve(results[0].refreshtoken);
        }

    })
});

Edit:

However, since the result of await is obtained from the value passed to the resolve, we don’t need to assign tokenyay inside of the callback.
We can use tokenyay = await... instead.

tokenyay = await new Promise((resolve, reject) => {
    pool.query(query, (error, results) => {
        if (error) reject(error);

        if (!results[0]) {
            console.log("No results");
            resolve(); // give `undefined` to the `await...` and make it stop waiting
            return;
        } else {
            console.log("results: " + results[0].refreshtoken);
            resolve(results[0].refreshtoken);
        }

    })
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading