2017年5月12日 星期五

[jquery] deferred and promise

 jquery   deferred    promise  


Introduction


This article will shows the basic usage of deferred and promise in jquery.



Sample code






Implement



deferred and promise

function getData(filter) {
    var deferred = $.Deferred();
    try {
        //Do ajax calls
        deferred.resolve(data);
    }
    catch (e) {
        deferred.reject(e);
    }
    return deferred.promise();
}


getData().then((data) => {
    //callback…
}).fail(e => { console.log(e); });


Use $.when to deal with promises

$.when(getData(filter1), getData(filter)).done((data1, data2) => {
    //callback…
}).fail((e) => {
    console.log(e);
});




Reference




沒有留言:

張貼留言