Search code examples
javascriptjqueryes6-promise

How to transform three chained callbacks (AJAX) to Promises in Javascript


I have this code:

$.ajax({
    method: 'GET',
    url: 'a.php'
}).done(function(res){
    $.ajax({
        method: 'POST',
        url: 'b.php',
        data: {data: res}
    }).done(function(res){
        console.log(res);
        $.ajax({
            method: 'POST',
            url: 'c.php',
            data: {data: res}
        }).done(function(res){
            console.log(res);
        });
    });
});

As you can see, it's just three AJAX functions. The second one depends on the first one and the third one depends on the second one.

How can I transform this to promises to make avoid using the callbacks and to make the code easier to read?


Solution

  • With jQuery promises it should look like this, with clear separation of concerns between the individual fetches:

    function a() {
        return $.get('a.php');
    }
    
    function b(res) {
        return $.post('b.php', {data: res});
    }
    
    function c(res) {
        return $.post('c.php', {data: res});
    }
    
    function d(res) {
        console.log(res);
    }
    
    a().then(b).then(c).then(d);