ππ-πππππ δ½ Posted June 4 Share Posted June 4 In this tutorial, you'll learn all about Asynchronous JavaScript. But before we dive into that, we need to make sure you understand what Synchronous code is and how it works. What is Synchronous Code? When we write a program in JavaScript, it executes line by line. When a line is completely executed, then and then only does the code move forward to execute the next line. Let's look at an example of this: let greet_one = "Hello" let greet_two = "World!!!" console.log(greet_one) for(let i=0;i<1000000000;i++) { } console.log(greet_two); Now if you run the above example on your machine you will notice that greet_one logs first. Then the program waits for a couple of seconds and then logs greet_two. This is because the code executes line by line. This is called synchronous code. This creates lot of problems. For example, if a certain piece of code takes 10 seconds to execute, the code after it won't be able to execute until it's finished, causing delays. Now, setTimeout is asynchronous so it runs in background, allowing code after it to execute while it runs. After 10 seconds, Asynchronous will print because we set a time of 10 seconds in setTimeout to execute it after 10 seconds. In this tutorial, we will study asynchronous JavaScript in detail so you can learn how to write your own asynchronous code. I just wanted to give you a taste of async JavaScript using in-built functions to whet your appetite. function compute(action, x, y){ if(action === "add"){ return x+y }else if(action === "divide"){ return x/y } } console.log(compute("add",10,5)) console.log(compute("divide",10,5)) In the above example, we have two operations. But what if we want to add more operations? Then the number of if/else statements would increase. This code would be lengthy, so we use callbacks instead: https://www.freecodecamp.org/news/asynchronous-javascript/#:~:text=In JavaScript%2C there are two,failure) of an asynchronous operation. Link to comment Share on other sites More sharing options...
Recommended Posts