Skip to content

24 Asynchronous

Biswajit Sundara edited this page Aug 18, 2023 · 1 revision

1. Synchronous Code

Synchronous code is executed in sequence

  • each statement waits for the previous statement to finish before executing.
  • For example Java code languages are synchronous and it executes line by line.
execution starts  ----       statement 1

after st1 is completed ---   statement 2  

after st2 is completed ---   statement 3 

2. Asynchronous Code

  • Asynchronous code doesn't wait. If it calls a method and the statements are getting executed,
  • It will not wait for the method to complete and start executing other methods.
  • Java Script/ Type Script codes are asynchronous and it doesn't execute in sequence.
execution starts  ----       statement 1

doesn't wait for st1   ---   statement 2  

doesn't wait for st2   ---   statement 3 
  • The asynchronous nature has a purpose, if we talk about web page rendering then asynchronous calls really help.
  • Means it starts loading the components one after another but doesn't wait for one component to finish loading before starting to load another.
  • However when it comes to automation script design, it's a challenge.
  • If the methods for page2 are invoked before executing the methods for page1 then the script is going to fail.

3. Example

JavaScript functions do not wait for one function to complete the execution before moving to another.

  • In the below example, it fires the function myFirst() but doesn't wait for the function to complete.
  • It will print Good Bye first and then after one second it will print Hello.
  • Now that's a problem, during run time we don't know which function will complete first
  • and if it executes another function we might not get the expected result.
  • Consider a scenario where we are saving a document before its edited completely,
  • or showing the result of a calculation before all parameters are fetched.
  • We need synchronization to solve the problem and call back, Promises are the ways to handle it.
function myFirst() {
    setTimeout(()=>{
       console.log('Hello');
    }, 1000);
  }
  
  function mySecond() {
    console.log('Good Bye');
  }

  myFirst();
  mySecond();

Clone this wiki locally