Run Ajax first

Asked

Viewed 42 times

0

The last line of the code below is the first to be executed, and I need the function containing this ajax to return true or false, but when I put to return inside Success,error or complete it does not work.

error: function (response) {
        if (((response.responseText.split("{")[1]).split("}")[0]).split(":")[1]) {
            confirmationValue = true;

        } else {
            confirmationValue = false;
        }
    },
    complete: function () {
        console.log(confirmationValue);
        return confirmationValue;
    }
});
console.log(confirmationValue);

Thank you!

  • Ajax, as the name itself says is asynchronous, so Return will make no sense. You can try using async/await, example click here

1 answer

0

You can use the Sync and await of ES6, this way you make the rest of your code wait for the result of your ajax function to continue the code, in your case awaits the boolean return to give sequ

    async  function executar(){
    return $.ajax({
    'url': 'https://swapi.co/api/people/1',
    'metod': 'GET',
    success: async function(data){
        return data
    }
  })
}

async function chamaFuncao(){
  await executar()
  .then((res) =>{
        alert(res.name)
  })    

  alert('Continua a execução')

}

chamaFuncao();

See the example on Jsfiddle

Browser other questions tagged

You are not signed in. Login or sign up in order to post.