user15334378
user15334378

Reputation:

Nodejs: Wait for API response during the execution of query

I am taking an email from the user and checking it in the database(DB2). After that I am sending an HTTP get request to further verify that email from a remote server. After that I am executing the query to verify the user password. However, I am facing a race condition here. My query for password verification begins executing without waiting for the API response from the remote server. How can I resolve that?

Here's my code:

conn.query(searchDB, [email], (err, results) => {
      if(!err)
      {
        if(results.length == 0)
        {
          res.send("UnAuthorized");
        }
        else
        {
          // I get the response from the below request
          samaccount = results[0].samaccount;

          http.get(`API-endpoint/${samaccount}`, (res) => {

            let data = '';

            res.on('data', (chunk) => {
              data += chunk;
            });

            res.on('end', () => {
              newdata = JSON.parse(data);
              if(newdata.accountStatus == true)
              {
                samaccountvalid = true;
                console.log("User Authorized as per sam account");
              }
              else
              {
                samaccountvalid = false;
                console.log("User NOT Authorized as per sam account");
                return;
              }
            });
          }).on("error", (err) => {
            console.log("Error: " + err.message);
          });
          
          //at the same time this starts executing I want to wait for the above request to complete
          if(samaccountvalid == true)
          {
            console.log("Password is being compared");
            .....comparing password here.....
          }
          ........

Any help would be appreciated. Thanks!

Upvotes: 1

Views: 219

Answers (1)

omarwaleed
omarwaleed

Reputation: 681

Your request to the remote API server is a stream. A stream will receive data on chunks and trigger the event end when it's complete. Similar to a promise or a callback, the async code will execute and get a response at a later time which means that the password check will execute before the end event is ever triggered.
You have 2 ways of handling this:

  1. move all your code inside the end event
  2. If the http.get function can return a promise with the entire payload, consider changing the conn.query callback function to an async function which enables you to await the response from the http.get function first and use the response in your password checker method

Upvotes: 1

Related Questions