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

Time:04-06

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".

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;
    };

CodePudding user response:

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);
        }

    })
});
  • Related