Asynchronous Programming
Asynchronous Programming
Asynchronous Programming is achieved in JavaScript by using Web APIs that process code on separate threads. The Web API's send their processed results back as tasks on the event queue. These tasks are defined by callback functions passed into the Web APIs. This allows JavaScript to achieve multi-threading in a single threaded run time.
Synchronous vs Asynchronous Programming
Imagine trying to run a slow task synchronously. It will take a long time to finish processing and will prevent other tasks from running.
Notice how the slowTask function takes a long time to process and prevents other fast tasks from processing:
Asynchronous programming is great because it prevents slow tasks from blocking faster tasks from processing. Asynchronous code will only run when the call stack is empty.
Notice how asynchronous code prevents slow tasks from blocking other faster tasks: