Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

node.js - NodeJS IF statement in an async function doesn't execute even though it's condition is met

I have a socket io application written in NodeJs. It has an emit timeout feature that my socket server application will receive from the client and will check my mongoose database for some data. I have an IF statement that checks if the data returned is true and executes some code.

exports.timeout = async (ref, clientdata) => {

 try {
    let resp = await Gc.find({'ref': ref});

    for (const ele of resp) {
      let mongodata = ele.data;
         
         if (mongodata === clientdata) {
             do-something;
         }
     }
  } catch (err) {
    console.log(err)
  }
}

The timeout function is called from one or multiple clients via socket io.

The first time a client calls the timeout function, it will not execute the code in the IF block even though the if condition is met.

The strange thing is that the second client that calls the timeout function will execute the code in the IF block when the if condition is met. It works with the third, fourth, and subsequent clients.

I have some use cases when only 1 client sends the timeout event and the program can't continue as the IF condition is not executed.

Any idea why it's behaving like this?

question from:https://stackoverflow.com/questions/65830629/nodejs-if-statement-in-an-async-function-doesnt-execute-even-though-its-condit

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, I have found a partial answer.

The IF condition is failing, as I use the "===" strict equality operator. For a yet unknown reason, the response from the Mongoose Find query returns a different variable type on the first execution compared to subsequent executions.

I'm using the "==" operator which does type correction and the IF condition matches perfectly.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...