Synchronous vs Asynchronous

Video

JavaScript Notes

JavaScript
    // SYNCHRONOUS FUNCTIONS
    let log = console.log; 
    let a = 5;
    let b = 50;
    
    let a1 = (function ( ) { return 5}) ( )	    // This is a IIFE, which will return a value
    let b1 = (function ( ) { return 50}) ( )	// This is a IIFE, which will return a value
    
    log ( a1 );
    log ( b1 );
    
    let a2 = function (num) {return 5 * num} 
    let b2 = function ( ) {return 50}
    log (a2(b2( )) );

    // ASYNCHRONOUS FUNCTIONS
    /**
    setTimeout, callbacks for geolocation, Promises, fetch, ajax, filesystem, interaction, database calls, even DOM event listeners
    **/
    
    let a3 = 100;
    setTimeout(function( ) { a3++; log (a3) }, 0);	// a3 here will return out to the console as 101 
    log(a3);	                                    // a3 will still log out to the console as 100
    setTimeout(function( ) { log (a3) }, 0);	    // a3 here will return out to the console as 101 
    
    let p = new Promise(function(resolve, reject) {
        setTimeout(function( ){
        resolve("Yo!");
        }, 0)
    });
    log(p);	                    // will return object, Promise {<Pending>}
                                // it will also not return "Yo!" as that has been set aside
    setTimeout(function( ) {
        log(p);	                // this log(p) will return Promise{<resolved>"Yo!"}, after 10ms
    }, 10);
    log(p);	                    // will return object, Promise {<Pending>}
                                // it will also not return "Yo!" as that has been set aside
    p.then(function(val){
        log(val);	            // returns p, as soon as the promise has been resolved!
    })