2014-10-27 70 views
0

我不明白,諾言/遞延非常......我有類似的東西:承諾延期AJAX API jQuery的

function callAjax() { 
    return $.ajax({ 
    type: 'post', 
    dataType: 'jsonp', 
    data: {status: status, name: name}, 
    url: '/test', 
    xhrFields: { 
     withCredentials: true 
    } 
    }); 
} 

function connectAjax() { 
    var msg = 'doesnt work'; 
    var promise = callAjax(); 

    promise.then(function(data, textStatus, xhr) { 
    msg = 'it worked !'; 
    }, function(data, textStatus, xhr) { 
    msg = 'it failed !'; 
    }); 

    console.log(msg); // output 'doesnt work' 
} 

我已經嘗試了很多不同的東西(總,做等。 ),但無法使其工作。

我使用jsonp但我的請求不是跨域。我希望服務器發出500個錯誤請求。

+0

Ajax請求的異步執行。 '.then()'將在ajax執行成功/失敗。 console.log()將在** ajax完成之前執行**。所以毫不奇怪'msg'是「不起作用」。在互聯網上閱讀JavaScript中的異步編程。 – Regent 2014-10-27 13:38:58

回答

1

舉個例子來說,你必須把'console.log(...)'語句放在你用.then(..,..)在promise上註冊的兩個回調函數中。

您必須記住只有在ajax調用完成時纔會調用promise回調函數。 但是,您的腳本不會等到這發生,'console.log(msg);'在ajax調用返回之前執行。

這是JavaScript的非阻塞性質的一個很好的例子。

爲了更詳細的瞭解查找資源的JS事件循環: https://thomashunter.name/blog/the-javascript-event-loop-presentation/ Understanding the Event Loop