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("/");
})
Please, How to add promise and wait to this code?