0

I created a global function where Axios calls a URL and waits for a response (and returns true or false)

function ajaxRequestTrueFalse(url)
{
    if(url == null)
    {
        var e = new Error("Veuillez saisir une URL");
        throw e;
    }

    axios.post(url)
        .then(function(response){
            if(response.data.code === 200)
            {
                return true;
            }
            else
            {
                return false;
            }
        });
}

window.ajaxRequestTrueFalse = ajaxRequestTrueFalse;

But when I try to call it from somewhere:

var result = ajaxRequestTrueFalse(myUrl);
console.log(result);

I get directly "undefined" and only afterwards, the call from axios starts.

I would like to directly recover the expected result in my function, but I do not understand why it does not work

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
eronn
  • 1,690
  • 3
  • 21
  • 53
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Nick Parsons Mar 29 '20 at 12:28
  • Not really, I don't understand :s – eronn Mar 29 '20 at 12:42
  • when you return from your `ajaxRequestTrueFalse`, you are actually returning to the `function(response){` function which is called by JS (not your code). So, your ajaxRequestTrueFalse function isn't returning anything. Since the code inside `function(response){` gets called later on (as it takes some time to perform the post) you need another way to retrieve the result from your callback. I suggest you use a Promise (as shown in the link I linked). Or simply return the promise returned by `axios.post()`, and then use `.then()` on your call to `ajaxRequestTrueFalse()`. – Nick Parsons Mar 29 '20 at 12:49
  • Oh okay it works better now, thanks ! – eronn Mar 29 '20 at 13:41

0 Answers0