Is JavaScript Promise Sync or Async?

TLDR; Any code in Javascript or Typescript that uses the word “promise” is asynchronous.

What Does Async Mean?

When coding asynchronously it means that your code is running on a different thread or CPU core than the main program that started the process. This leaves the main thread free to do important jobs like keeping the user interface responsive.

How is Promise Related to Async or Callbacks?

Async code used to use callbacks way back when. These are functions that get called when the long running task has been completed.

Analogy: Imagine sending your little brother to the shops and telling him to call you when he gets there so you can give him your order. This is asynchronous as you can do another useful task whilst he’s driving there. The phone call (callback) tells you the driving task has ended and he’s ready for instruction *.

* This is how all little brothers should behave, awaiting instruction from big bro 😉

Back to code: This callback system is also known as a promise, as in: I promise to call you when my task is finished.

Async and promises are the same thing.

Async delivers exactly the same experience as a promise or callback, except it makes it MUCH more readable. Async is what we call syntactic sugar.

//The following produce exactly the same result, both keeping long tasks off the main thread

//PROMISE Version
doSomething ((result) => {
  //CALLBACK code to run after doSomething has finished
  process(result)
});

//asynchronous syntactic sugar Version
let result = await doSomething()
process(result)

Where Did Async Come From?

Historically, as CPUs got more cores and threads we needed a way to make use of the parallel processing power. This is where the idea of offloading code to another thread came about.

Async is short for asynchronous which means “happening at the same time as something else”. On a modern CPU that means you can have 32 things happening simultaneously (or even more with clever hyper threading technology!).

Should Your Code be Async?

Well, it depends. You shouldn’t always use async over sync or vide versa. There are specific situations where you would choose differently.

Most beginners think that async keeps your UI thread free therefore all code should be asynchronous, but that is definitely not the case.

See this post to find out why: is async better than sync?