Javascript Promises, Async and Await

October 30, 2022 note-to-self

As always: This is for my own understanding. Please don't assume it is 100% correct.


await pauses the execution of an async function until the awaited promise resolves or rejects.

When the promise is resolved, the next time around, the event loop will unpause and execute at the line after await.

If you don't use await, it won't pause there, but immediately move on while the promise is unresolved. The promise will eventually resolve asynchronously, but most likely after the data or state being waited on needs it.

If several functions rely on data from one another, await is essential to ensure proper sequencing.


Use await or .then() to define dependencies between tasks. Tasks that don’t depend on each other can run concurrently.


Think of it this way: Your live is on the "event loop". If you send an email, a synchronous function would wait until you received a reply, and then you could do something else. You would sit there staring at the screen until you got the reply.

An asynchronous function lets you do other tasks - send more emails, go to the bathroom, grab coffee, etc. Then, when the email comes back, you can act on it.


In JavaScript, you can write sequential or synchronous code, where each line is executed one after the other, in the exact order they appear in your script. This is the default behavior of JavaScript, and you don't need anything special to make it happen.


Also: await must be inside an async function. This is because await is used to pause the execution of the function it's in, but it allows the rest of the program to do other things. It's just that one function that is paused.

When you use await in an async function, only that specific function is paused at the point of the await. The program itself (or other asynchronous functions) isn't blocked.


Promise.all() - when all the promises in the array are complete, it returns. If there are three promised in the array and two take 3 seconds and one takes 5 seconds, the Promise.all() promise will resolve after 5 seconds when the 3rd one is complete. If any promise of the three is rejected, then the whole thing fails.

const fetchUsers = fetch("/api/users");
const fetchPosts = fetch("/api/posts");

const [users, posts] = await Promise.all([fetchUsers, fetchPosts]);

So, fetchUsers and fetchPosts run simultaneously, but Promise.all() makes sure they are both done before continuing.


Promise.allSettled() - if waits for all promises to complete, regardless of whether they resolve or reject. Use this if it is okay for some of the promises to complete, even if one rejects.

These posts are for my own understanding. Reader beware. Info may be wrong but it reflects my current understanding.