Asynchronous vs. Synchronous Code
By: Charles Tillmon

Asynchronous vs. Synchronous Code

JavaScript is a single threaded, synchronous programming language. This means when code is executed by the JavaScript engine the current task must be completed before the engine can move on to the next task. For most code the wait time isn’t noticeable but for larger functions this becomes an issue. The issue that arises is that while the code is waiting for completion, no other actions can be taken. For example, if you submit information for a contact form on a site you would have to wait for a response from the server. If the server takes 3 minutes to respond (or more likely timeout); the web page in that time would be unresponsive. Sure, you can click a button, but nothing will happen until the response from the server is received for the current task. Imagine being at the bank and there is only one receptionist. Everyone would be in a single file line and your place in line determines when you would taken care of. This is exactly how synchronous blocking languages work.

More recently the use of asynchronous code has helped relieve this issue. Asynchronous code allows all tasks to be executed at the same time, but the current task doesn’t hinder the completion of other tasks. However, as we stated JavaScript is single-threaded, so the asynchronous code is a product of the host in which it is implemented and not JavaScript itself. In the above example where we submitted the data via a contact form, asynchronous code would allow us to interact with the page because the response coming back from the server would not hinder other tasks. Now clicking the button would perform exactly as expected.

Understanding the difference between these two types of code will allow you to properly implement them in projects. While it may be tempting to use asynchronous code in every situation; this can lead to some undesired results. Some code is dependent on the other code being executed first and, in these situations, a synchronous style would be preferred. Therefore, we believe a foundational understanding of a language is key to optimizing the outputs. 

要查看或添加评论,请登录

社区洞察

其他会员也浏览了