Callbacks, Promises & Async/Await

Carolina Cobo
4 min readAug 30, 2022
source: Freepik

I’m currently diving more deeply into how JS works and I’ve been watching Will Sentance’s JavaScript: The Hard Parts course. One of the sections is about Promises and Async/Await and I have to say it still was a bit of a mystery for me, so after watching the section of the course I decided I’d like to do a bit more reading on it on the MDN docs.

I think to start, callbacks would make sense to see how it’s improved with promises and made our life easier.

Callbacks

Function passed inside another function as an argument, that is then called in that function to perform a task.

console.log('First');
console.log('Second');

setTimeout(()=>{
console.log('Third');
},2000);

console.log('Last');

This snippet would return this:

First
Second
Last
Third

This is because the setTimeout is set up to wait for 2 seconds so the threat of execution will continue, and then come back to it. This method was good until you needed to make multiple calls, and to do so you’d have to nest the functions to get the desired behaviour. This would cause end up in what was referred to as Callback Hell or Callback Pyramid of Doom.

Promises

The MDN docs define a Promise as an object that represents the eventual completion or failure of an asynchronous operation.

A promise is a returned object to which you attach callbacks, instead of passing callbacks into a function.

Why use them?

Using promises will guarantee you some outcomes that you wouldn’t get from callbacks such as:

  • If the callback is added with a .then() it will never be invoked before the current event loop run has been completed.
  • The callbacks will be invoked even if they were added after the asynchronous operation that the promise represents has succeeded or failed.
  • You can add multiple callbacks just by calling .then() several times. They will be invoked one after another, in the order in which you placed them in the code block.
  • Chaining, which is worth getting into more detail.

Chaining

--

--

Carolina Cobo

Frontend Software Engineer @ Genesys | Career switcher