DEV Community

Rodolfo Machirica
Rodolfo Machirica

Posted on • Edited on

Asynchronous Coding in JavaScript

Synchronous vs asynchronous operationsIn this post we are going to explore and learn some concepts about asynchronous programming. We will talk about what asynchronous coding is and the importance of it in web development, and async operations using callbacks.

JavaScript is a synchronous programming language. The execution of a JavaScript program occurs in a single thread, line by line, without skipping any line of code. Single threadiness, however, exposes an issue: different lines or blocks of code in functions take different amount of time to run, thus, there would be a long wait time when time expensive operations are reached. So, this is where asynchronous approach come in to save the day! Asynchronous JavaScript makes possible for multiple and complex actions to happen while the program is running but without blocking the main thread.

Why Asynchronous coding

According to Javin Paul on Top 5 Programming languages for Web development in 2022, Jan 13, 2021, on medium.com, most web development is done with JavaScript. Asynchronous coding is particularly relevant for frontend development. The problematic of time lag (mentioned in the paragraph above) that occurs when heavy duty programs are in execution or a request to an API is made, in the context of web development, is very important as it affects the user experiences with the UI. A user considers a website to be slow if the response for any action they perform on it takes more than 100ms, said Divyanshu Bhatnagar in a blog post titled How to Optimize Long Tasks (Blocking Javascript) in Browsers on, Jul 11, 2021, on medium.

Handling asynchronous events

In JavaScript, there are various ways in which code can run asynchronously. The most commonly used in these recent years are: Promises and Async/await; but for matters of legacy, we are going to talk about the old and classic way of handling asynchronous codeβ€Š-β€Šcallbacks.Β 
Callback functions which simply in this context refer to functions that are passed into other functions as parameters or arguments, with the purpose of running when an event associated with that callback is initiated or some operation finishes. See bellow an example of an asynchronous code using the callback approach:

const btn = document.createElement('<button></button>');
  btn.textContent = "Click to register";
  btn.addEventListener.on("click", ()=>{
    console.log("Welcome, you are now a member");
});

Enter fullscreen mode Exit fullscreen mode

addEventListener is our function that is taking in an event of type "click" and an anonymous callback function that sits there waiting for the event "click" to occur and then it executes and returns the result of that operation to the addEventListener function which then gives the response back to the user.
The example above is a typical occurrence in webpage or interactive UI applications where users can perform a varied set of actions from clicking buttons, making requests to a server for data, etc. Here is an example of an asynchronous program using a callback for requesting data from a server:

  //we create a variable to hold an image tag
  const $img = $('img');
  // we make our a.jax call 
  $.ajax({
    url: "http://fakeimageapi.img", 
    dataType: {json: true},
    //callback to run if the request is successful
    success: ((data) => { 
    $img.append(result.url);
   }),
    error: () => {console.log ("image not found")}
});
Enter fullscreen mode Exit fullscreen mode

Callbacks are great and they help us run programs asynchronously. However, they present a major drawback: in cases of nested callbacks, which does happen, they can confuse readers and even the author of the code, and for this reason alone, we have Promises and Async/await, concepts to be covered in the next article.

conclusion

Asynchronous coding is extremely important in the web development as it addresses the issue of UI freezing caused by the complex and time expensive operations.

Sources consulted:

  1. https://iq.opengenus.org/asynchronous-programming-in-javascript/
  2. https://www.i-programmer.info/programming/theory/8864-managing-asynchronous-code-callbacks-promises-a-asyncawait.html
  3. https://blog.logrocket.com/understanding-asynchronous-javascript/
  4. https://eloquentjavascript.net/11_async.html
  5. https://www.webucator.com/article/how-to-use-the-callback-function-in-ajax/
  6. https://medium.com/codebuddies/getting-to-know-asynchronous-javascript-callbacks-promises-and-async-await-17e0673281ee
  7. https://www.twilio.com/blog/asynchronous-javascript-understanding-callbacks

Top comments (0)