water asyncfall

use of asyncwaterfall approach to make async calls

by Kamal Rawat

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/async/2.1.2/async.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input type="button" value="rendergrid" id="btnone"/>
<br/>
<span id="spnstatus"></span>
<br/>
<div id="tablecontainer">

</div>

JavaScript

var records = 		[	
										{name:'Record1',id:'101'},
										{name:'Record2',id:'102'}
                 	];


$(document).ready(function(){
	$('#btnone').click(function(){
  	async.waterfall([
      getData,
      printData,
      addData,
		], function (err, result) {
      console.log(result.map(x=>x.name)); //this result is being passed from 'addData'
      $('#spnstatus').html('Data Retrieved successfully...');
      $('#tablecontainer').append(  '<table>' );
        for(i=0; i < result.length; i++){
           $('#tablecontainer').append( '<tr><td>' + result[i].name + '</td></tr>' );
        }
      $('#tablecontainer').append(  '</table>' );
      console.log('grid rendered completely');
	 });
   
    function getData(callback) {
        console.log('getData function called');
        $('#spnstatus').html('fetching data in progress...');
        setTimeout(function(){
          callback(null, records);
        },3000);
        
    }
    
    function printData(arg1, callback) {
    		var names = arg1.map(x => x.name);
        console.log(`printData called with  ${names}`);
        setTimeout(function(){
        	callback(null); // shows callback function with no error
        },4000);  
    }
    
    function addData(callback) {
	      $('#spnstatus').html('adding new data in progress...');
        var newRecord = {name: 'Record3', id: '103'};
        records.push(newRecord);
        console.log('record added successfully');
        callback(null, records);
    }
  });
})