jQuery deferreds and promises - .then() vs .done()

后端 未结 10 1479
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-22 06:16

I\'ve been reading about jQuery deferreds and promises and I can\'t see the difference between using .then() & .done() for successful callbacks

10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-22 06:48

    deferred.done()

    adds handlers to be called only when Deferred is resolved. You can add multiple callbacks to be called.

    var url = 'http://jsonplaceholder.typicode.com/posts/1';
    $.ajax(url).done(doneCallback);
    
    function doneCallback(result) {
        console.log('Result 1 ' + result);
    }
    

    You can also write above like this,

    function ajaxCall() {
        var url = 'http://jsonplaceholder.typicode.com/posts/1';
        return $.ajax(url);
    }
    
    $.when(ajaxCall()).then(doneCallback, failCallback);
    

    deferred.then()

    adds handlers to be called when Deferred is resolved, rejected or still in progress.

    var url = 'http://jsonplaceholder.typicode.com/posts/1';
    $.ajax(url).then(doneCallback, failCallback);
    
    function doneCallback(result) {
        console.log('Result ' + result);
    }
    
    function failCallback(result) {
        console.log('Result ' + result);
    }
    

提交回复
热议问题