0

I wrote this code for testing. I expected it to execute sequensially. and the out put to be: 1- Search for user no. 1
2- Search for user no. 1
3- search for user no. 1
4 user 1 Exist ( if exist ) or 4- user 1 not exist ( if not)

but the statments printed in a diffrent order, the statment before the find printed together and the statments inside the find printed together. I added a delay time before executing the next loop to allow the find to complet but not success.

How to execute solve this problem and execute statments in order.

app.get("/alert2", function(req, res) {
  for (let y = 1; y < 5; y++) {
    sleep(1000).then(() => {
      console.log("1-   Search for user no. " + y);
      console.log("2-   Search for user no. " + y);
      User.findOne({ firsName: "Abdelmenem" + y }, function(err, foundList) {
        console.log("3-  Search for user no. " + y);
        if (!err) {
          if (!foundList) {
            console.log("4- user " + y + " not Exist");
          } else {
            console.log("4-  user " + y + " Exist");
          }
        } else {
          console.log(err);
        };
      });
    });
    y1 = y;
  };
  console.log("finished : " + y1);
  res.redirect("/");

})

enter image description here

Please, How to add promise and wait to this code?

abdo M
  • 1
  • 1
  • `User.findOne` is an aynchronous statement. The `for` loop continues synchronously after the `User.findOne` query has been sent to the database (that's why the four pairs of `1-` and `2-` statements come first), but the callback `function(err, foundList)` is executed asynchronously, only after the database operation has completed. But that's alright, you need not wait for the first database response before submitting the second query. – Heiko Theißen Oct 07 '22 at 16:10
  • Use the promise interface on your database (not the callback interface) and then use `await` on that promise inside the loop. – jfriend00 Oct 07 '22 at 16:23
  • @jfriend00 can you please update my code to use it. – abdo M Oct 08 '22 at 18:48
  • Can you share why are you using a for loop? what are you trying to achieve with this loop? – Haroon Azhar Khan Oct 09 '22 at 12:32
  • Does this answer your question? [Wait for callback before continue for loop](https://stackoverflow.com/questions/14408718/wait-for-callback-before-continue-for-loop) – derpirscher Oct 09 '22 at 14:08
  • I want to insert a large number of records for testing puros. @HaroonAzharKhan – abdo M Oct 11 '22 at 22:25
  • I want to pause the for loop until the findOne function completed and then continuo executing the for loop, but now the for doesn't wait findOne and continuo. – abdo M Oct 11 '22 at 22:31

0 Answers0