0

How I call methods in my page using sync methods (wait for the answer of each one) ?

I did tests with async : false to test, but its not work in jQuery current version.

    function mainAction()
{
    if (!action1())
    {
        console.log('error : action1');
        return false;
    }

    if (!action2())
    {
        console.log('error : action2');
        return false;
    }

    console.log('done');
    return true;
}

And the basic structure in each function that I call:

function action2()
{
    $.ajax({
        type: "GET",
        url: someurl...,
        dataType: "html",
        timeout: 30000,
        data: 
        {
            //somedata... 
        },
        success: function(data)
        {
            response = $.parseJSON(data);
            return (response.status == 'ok');
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            console.error(textStatus + ' ' + errorThrown);
            return false;
        },
        complete: function(jqXHR, textStatus)
        {

        }
    });         
}

The return on each statement (success/complete/error) not affect the return of the entire function, what I need to force the return (boolean) of the function after the ajax finish ?

MCunha98
  • 81
  • 3
  • 12
  • 2
    Embrace the asynchronous nature of these operations. Either pass callback methods into your `action2` method, or have `action2` return a Promise. – StriplingWarrior Jul 11 '18 at 16:09
  • @StriplingWarrior do you know some link for I see an example ? – MCunha98 Jul 11 '18 at 16:13
  • 1
    Possible duplicate of [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) – Heretic Monkey Jul 11 '18 at 16:15
  • @HereticMonkey thanks for the link, but actually it is too large and confuse. Sometimes I saw the 'jump' from function to callbacks, and I just want to return a boolean after a ajax call function (is really simple that I want), but is to confused to understand the examples. – MCunha98 Jul 11 '18 at 16:22
  • 2
    Asynchronous code is not something you're going to get without some work and thought. It might take you more than the 6 minutes you gave to reading the answer. Please take some time, read through the answers slowly or read through some tutorials online. The investment you make now will pay off in the long run. – Heretic Monkey Jul 11 '18 at 16:26
  • I got some pieces of this big reply to understand, basically I want to put the $.ajax as return into a variable, but anything that I put inside success,error or complete don't change anything because the return is the $ return... var ret = $.ajax({...}); and I did this test: console.error(ret); console.error(ret.response); return ret.then(function(response){return response.status === 'ok';}, function(){return false;}); – MCunha98 Jul 11 '18 at 16:29

0 Answers0