-1
 we are trying to change some calls in the application from sync to async then i read the post

"Call An Asynchronous Javascript Function Synchronously" so when i call the callThis() I am getting the output as: "Success" "failure" but I need the output as "Success" "KATE success"

Can you guys suggest me a solution for this, not the callback or timeout but still an efficient technique when changed from sync to async

function callThis()
{
    if(kate())
    {
      console.log("KATE success")
    }
 else
  {
   console.log("failure")
  }
}
function kate()
{
  $.ajax({
        url: "www.google.com" (http://www.google.com),
        type: 'get',
        async: true,
        timeout: 10000,
        success: function (data) {
            console.log("Success");
        },
        error: function () {
            console.log("FAIL!!!");
        }
    });
}
Community
  • 1
  • 1
Kate Spade
  • 47
  • 3
  • 12

2 Answers2

2

The solution isn't to call it synchronously, but to work with the asynchronous nature of ajax

function callThis() {
    kate().done(function(result) {
        if ( result ) {
            console.log("KATE success")
        } else {
            console.log("failure")
        }
    }).fail(function(error) {
        console.log(error);
    });
}

function kate() {
    return $.ajax({
        url: "www.google.com",
        type: 'get',
        async: true,
        timeout: 10000
    });
}

note that getting google.com will fail due to the same-origin policy

adeneo
  • 312,895
  • 29
  • 395
  • 388
  • I don't want to change the function kate() because everyone is using it so If I change that I need to change the whole thing , so can we use promise:done or then or any other solution which helps me – Kate Spade Jun 12 '15 at 16:56
  • Nope, it simpy can't be done without changing that function, either by returning a promise, using a callback or adding async false, which you shouldn't do. – adeneo Jun 12 '15 at 17:50
0

You could use the promise interface that jQuery returns (.done), like this:

function callThis() {
    kate().done(function(result) {
        if ( result ) {
            console.log("KATE success")
        } else {
            console.log("failure")
        }
    }).fail(function(error) {
        console.log(error);
    });
    console.log("KATE SPADE")
}

function kate() {
    return $.ajax({
        url: "www.google.com",
        type: 'get',
        async: true,
        timeout: 10000
    });
}

Even the asynchronous nature of ajax is now taken into account, I am still getting the output as:

KATE SPADE \n

KATE success

Community
  • 1
  • 1
Kate Spade
  • 47
  • 3
  • 12