在javascript中同步调用异步函数

时间:2015-06-11 22:53:00

标签: javascript asynchronous call

 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” 所以当我调用callThis()时,我得到的输出为:    “成功”    “失败” 但我需要输出为    “成功”    “凯特成功”

你们可以为我建议一个解决方案,而不是回调或超时,但从同步变为异步时仍然是一种有效的技术

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!!!");
        }
    });
}

2 个答案:

答案 0 :(得分:2)

解决方案不是同步调用它,而是使用 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
    });
}

请注意,由于同源策略

,获取google.com将失败

答案 1 :(得分:0)

您可以使用jQuery返回的promise接口(.done),如下所示:

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
    });
}

现在考虑到ajax的异步性质,我仍然得到输出:

  

KATE SPADE \ n

     

凯特成功

相关问题