2015-06-11 44 views
-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」 所以當我調用callThis()我得到的輸出: 「成功」 「失敗」 但我需要的輸出作爲 「成功」 ‘凱特成功’要調用異步函數同步在JavaScript

可以從同步改爲異步時,你們建議我一個解決方案,而不是回調或超時,但仍然有效技術

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

的解決方案是不同步調用它,但工作 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將失敗歸因於同源策略

+0

我不想改變功能凱特()因爲每個人都在使用它,所以如果我改變了我需要改變整個事情,那麼我們可以使用promise:done或者其他解決方案來幫助我 –

+0

不,它不能在不改變該功能的情況下完成通過返回一個承諾,使用回調或添加async false,你不應該這樣做。 – adeneo

+0

你能告訴我一個更好的方法使用回調 –

0

你可以使用承諾的界面,jQuery的返回(.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的TURE現在考慮,我仍然得到的輸出爲:

凱特·絲蓓\ n

KATE成功

+0

我需要的輸出是相反的,即KATE成功和KATE SPADE –