Callbacks, Promises & Async/Await
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.