Javascript
Sync vs Async functions

Synchronous functions

  • blocking
  • statements complete before next statement is run, aka program is evaluated exactly in order of the statements

Context

  • the need for asynchronous code arises because javascript is single-threaded in nature, aka two processes cannot run in parallel (at the same time)
  • we can simulate concurrency in javascript by breaking down long-running tasks into smaller asynchronous processes that can be interleaved with other processes without blocking its only thread
  • see parallelism vs concurrency (opens in a new tab)

Asynchronous functions

  • non-blocking
  • usually accepts a callback as a parameter and execution continue on the next line immediately after the async function is invoked
  • the callback is only invoked when the async operation is complete and the callstack is empty
  • heavy duty operations such as loading data from web server or querying database should be done asynchronously so that main thread can continue executing other operations instead of blocking