Synchronous vs Asynchronous programming

Don’t get confused anymore about Synchronous vs Asynchronous programming

Synchronous code will start from the top of the file and execute all the way down to bottom of  the file each line in order until it reaches the end it will stop.

Code example:

let a = 1;
let b = 2;

console.log('syncrhonous code');
console.log('a ->', a);
console.log('b ->', b);

Result:

Asynchronous code will start also at the top of the file and execute the code until get to the bottom file, but during that execution it will run some certain asynchronous functions, means that it will split out and execute that asynchronous code separately from the rest of our code and usually because it need to wait some operations that takes long period time.

So the asynchronous code will execute the code from top but if hit something that is asynchronous and then it will execute that code and also the rest of the code in the same time, and it do that for every async thing that found in the code file, so our code will execute in different order. 

Code example:

let a = 1;
let b = 2;

// Function that by nature is a asynchronous function
setTimeout(function() { // This function 
  // will be executed after 100 milliseconds
  console.log('Asynchronous code');
}, 100)

console.log('a ->', a);
console.log('b ->', b);

Result:

If you see the text ‘Asynchronous code’  is displayed after the other code even if this is declared before well this is because the SetTimeout doesn’t run the function until the 100 milliseconds happens and doesn’t block the rest of the code to be executed (we don’t need to wait that 100 milliseconds are completed to continue with the flow).

Check this example


Code example:

let a = 1;
let b = 2;

// This fetch is also asynchronous function
// The response time will depend of the server delay
// But because is asynchronous it will not block the execution
// of the other code
fetch('https://divercity-test.herokuapp.com/jobs').then(function() {
  console.log('fetch')
})

// Function that by nature is a asynchronous function
setTimeout(function() { // This function
  // will be executed after 100 milliseconds
  console.log('Asynchronous code', a);
}, 100)

console.log('a ->', a);
console.log('b ->', b);

Result:

Usually most functions that take functions as an arguments will be asynchronous code.

function myFunction(function two() {...}, function three() {...})

By Criss.