First let’s learn what is Synchronous and Asynchronous?
In very simple words,
Synchronous = Blocking
If a program is executed line by line, its called synchronous programming. Until first line finishes execution, second line will not be executed. But if all the lines start execution at same time and it is not blocking any other lines to be executed, is called asynchronous programming. Every asynchronous piece of code signals when execution is done. Signal is called as callback.
Example: Java is Synchronous programming langauge while NodeJS is Asynchronous programming language.
If we want to execute any asynchronous block of code in Selenium, we need to use executeAsyncScript method.
Syntax of executeAsyncScript :
java.lang.Object executeAsyncScript(java.lang.String script,java.lang.Object… args)
As per Selenium documentation:
window.setTimeout(arguments[arguments.length - 1], 5000);
Here, arguments[arguments.length – 1] is a callback function. To get last arguments we need to get the length and minus one. This method calls the function after 5 seconds to execute.
Let’s see above example in code:
Now, what will happen if we execute async code through executeScript method.
Change the above code as below:
This time execution control does not wait because JVM does not know about it. This is the reason, to execute asynchronous piece of code, we need to use executeAsyncScript.
Hope you will have clear understanding of method executeAsyncScript.
If you have any doubt, feel free to comment below.
If you like my posts, please like, comment, share and subscribe.
You have cleared my doubts on Asyn and Sync concept thanks alot !!!:)