Do not judge strictly - I just started to learn JavaScript.

I check the user's rights and if the user has the necessary rights, then the code is executed. I create an if in which I call a function from another js file. The problem is that js without waiting for a response, then executes the code and therefore the function returns undefined ...

Here is the code:

 if (verification(localStorage.getItem("client_id"), localStorage.getItem("verification"))){ 

...}

Function code from a separate verification.js file:

 function verification (client_id, verification){ $.ajax({ url: "/verification", method: "POST", async: false, data: { client_id: client_id, verification: verification, } }).then(function(res) { return res; }); 

}

How can I do if wait for an answer?

  • No way, but you already know about then ) - Igor
  • if ajax succeeds, the callback comes to the method success: url: "/verification", method: "POST", async: false, data: { client_id: client_id, verification: verification, }, success: function(res){ //ваш if, res - это то, что возвратит сервер }, - Vitaly Shebanits
  • Use await - And

1 answer 1

This is done in a different way - not the way you imagine it. Just put your if into a function that you pass to the then function. Like this:

 function verification(client_id, verification) { $.ajax( { url: "/verification", method: "POST", async: false, data: { client_id: client_id, verification: verification, } }).then(function(res) { if(checkResponse(res)) // приблизительно так; res – это ответ сервера { // ваш код... } }); } verification(localStorage.getItem("client_id"), localStorage.getItem("verification")); function checkResponse(res) { // ваш код проверки... return //... } 
  • The problem is that I repeatedly perform this test in different functions and on different pages, so I wanted to create a separate function to call from any pages, so as not to repeat the code ... - VaCool
  • @VaCool, everything is also simple here - transfer your check with the input data to a separate function and use it at least a thousand times later. - Bharata
  • so I want to do this ... Above I wrote how everything works for me now without a separate function ... - VaCool
  • @VaCool, I added my answer. Now it is clear? The checkResponse function checkResponse used at least a thousand times later. - Bharata
  • Thanks, check it out now - VaCool pm