JSFiddle - React, Tailwind, and code Playground

by Alexandre Simoes

HTML

<h1>Demostrate callbacks</h1>
<p>
Callback is a way to delegate the execution of an “outter” function to a caller function :)
</p>
<p>
Execution chaining is a bit of a hassle and usually done in a sequesce, not in parallel.
</p>
<h2>Three examples</h2>
<ul>
    <li>Call getUser function</li>
    <li>Call getLanguages function</li>
    <li>Call both functions and act only uppon success of both</li>
</ul>

JavaScript

// functions that perform ajax requests
var getUser = function(callback){    
    $.ajax({
        type: 'GET',
        url: '/echo/json',
        data: { json: { /*---*/ }, delay: 3 },
        success: function(){ callback('getUser success'); },
        error: function() { throw new Error('getUser error') }
    });
};
var getLanguages = function(callback){
    $.ajax({
        type: 'GET',
        url: '/echo/json',
        data: { json: { /*---*/ }, delay: 5 },
        success: function(){ callback('getLanguages success'); },
        error: function() { throw new Error('getLanguages error'); }
    });
};

// call getUser function
var t1 = new Date()*1;
getUser(
    function(resp){
        var deltat = new Date() * 1 - t1;
        console.log(resp + ' in ' + deltat + 'ms'); 
    }
);

// call getLanguages function
var t2 = new Date()*1;
getLanguages(
    function(resp){ 
        var deltat = new Date() * 1 - t2;
        console.log(resp + ' in ' + deltat + 'ms'); 
    }
);

// call both functions and only act uppon success of both
var t3 = new Date()*1;
getUser(function(resp1){
    getLanguages(function(resp2){
        var deltat = new Date() * 1 - t3;
        var resp = [resp1, resp2, 'in ' + deltat + 'ms'];
        console.log(resp); 
    })
});