Fell in love with Asynchronous programming
Asynchronous programming refers to the occurrence of events independently of the main program flow and ways to deal with such events. - wiki
Asynchronous (Async) programming are commonly used in:
- event-based (User interface in a browser)
- long-running operation (I/O)
- Making API call (our favourite Ajax calls.. :-))
Let take an analogy to understand it:
You went to the drive-through restaurant, ordered a burger, waited till you get it and then drives away. Other are in the queue waiting for their turn. That's synchronous, the most common way we built "c" or "Java" (excluding swing) programs. You may notice while you are waiting for your order other are also blocked and need to wait until you finish.
Suppose you went to a restaurant and order a burger. You get a receipt and until the time your order is ready you have waited outside queue and others are placing their orders. Now that's non-blocking way to work known as "Asynchronous".
Yes, we can create a new thread in Java which can perform two task concurrently. However, that is "Parallelism" not "Asynchronous". Beside that our system might have 8 or 12 core (at max.) and you can only run that much thread in parallel.
So if Asynchronicity is that good why not everyone is using it?
Many Programmers think/create their algorithm in a sequential manner, writing down an algorithm that does one thing after the other. However, in asynchronous programming, because you cannot say exactly when anything is going to complete and return a result. Execution order cannot be guaranteed in asynchronous programming.
As famously quoted:
Time is the most complex factor of state in your program - Kyle Simpsom
Many developers (including me in my early days) tend to ignore the concept of time while writing asynchronous program and find it difficult to accustomed it.
Is there any way to write asynchronous code synchronously?
Yes, "Promises" pattern allows you to think/write your asynchronous algorithms in a synchronous manner. Promises are a time-independent wrapper around a “future value,” which lets you reason about and compose them regardless of if the value is ready or not yet.
ES6 has introduced promises. There are also many libraries available which provide full fledge Promise implementation such as Asynquence or Q.
Asynchronous programming is great for faster execution of programs. People tend to use it more once they get customed to it. Give it a shot and share your experience.. :-).
Credit: Melting pocket watch by M. S. Polluk
nice way to explain asynchronous programming really like your resto example sir!!!
Async explained very cleverly. Nice points that differentiate between parallel and async programming. Thumbs up!!!
great