The goal is to achieve asynchronous code. Async code allows multiple things to happen at the same time. When you start an action, your program continues to run. When the action finishes, the program is informed and gets access to the result. We can achieve async code using two methods: callbacks and promises. With callback we pass a callback into a function that would then get called upon completion. With promises, you attach callbacks on the returned promise object.
Let’s make that pb&J from scratch using callbacks
This synchronous Peanut Butter & Jelly function runs in order, one function after another. but what if we had a function that needed to be ran first and other functions couldn't be ran until after this function finishes. Let’s think of making bread from scratch. you can’t put the peanut butter and jelly on the bread until it’s made so you must wait until its done. With synchronous code it doesn’t wait it just does it. How can we fix it?
We make an async callback so that we can make sure no other function runs until our bread is made. Let’s picture inside all the other functions there’s ample amounts of code to run. This can cause an issue because you can have plenty of nested callbacks inside one another. That leads to what we call callback hell. Callback hell can riddle code with bugs that are hard to catch. For this we need a way to make aync code while avoiding so many nested callbacks.
Let’s change our callback to a promise
Here we take our PB&J function and turn it into a promise. We will first return the makeBread function and then on the successful completion of that function we will return a promise that will pass in the next callback to be ran. Next, we will chain on the other function that will be ran after that in order. thus, making async function. As you can see the code is neither and we avoid callback hell.
We can also chain on an error message to the .catch() method and on that message "ewww crunchy peanut butter" because that will just ruin my sandwich.
Let’s make our promise a little bit neater by just passing in the callbacks.
Both callbacks and promises help make our code asynchronous. Making callbacks async can cause issues such as callback hell, so to avoid this we can use promises instead, doing this helps us avoid this pitfall while keeping our code async and neat.