js中同步與非同步處理的方法和區別總結

來源:互聯網
上載者:User

js中同步與非同步處理的方法和區別總結

 若要在使用ajax請求後處理髮送請求返回的結果,最好使用同步請求,下面為大家介紹下js中同步與非同步處理的方法和區別,感興趣的朋友不要錯過

在使用非同步請求時,有時需要將非同步請求的結果返回給另一個js函數,此種情況下會出現未等非同步請求返回請求結果,該發送請求所在js函數已經執行完後續操作,即已經執行return ,這樣會導致return的結果為空白字元。 

 

總結:若要在使用ajax請求後處理髮送請求返回的結果,最好使用同步請求。 

 

例如:以下例子會出現返回結果不正確的情況,因為ajax非同步請求還未執行完,函數已經執行return了, 

 代碼如下:

function fn(){ 

 

var result = " "; 

 

$.ajax({ 

url : 'your url', 

data:{name:value}, 

cache : false, 

async : true, 

type : "POST", 

success : function (data){ 

do something.... 

 

result = .... 

 

// 對ajax中返回的data進行處理 ,也會出錯 

 

return result ; 

 

1 非同步請求方式: 

 代碼如下:

$.ajax({ 

url : 'your url', 

data:{name:value}, 

cache : false, 

async : true, 

type : "POST", 

dataType : 'json/xml/html', 

success : function (result){ 

do something.... 

}); 

 

2 同步請求方式 

代碼如下:

$.ajax({ 

url : 'your url', 

data:{name:value}, 

cache : false, 

async : false, 

type : "POST", 

dataType : 'json/xml/html', 

success : function (result){ 

do something.... 

}); 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.