Promises to the rescue! What promises allow us to do is set up our code to say: "Don't worry about doing this right away or waiting for a response, keep going with this other important stuff and I promise I'll get back to you with the results"
Alright, lets get some keywords down so that you can know how to use promises. The first one, naturally, is Promise! The way you use it is by placing the new keyword in front of it to create a new instance of a promise object.
In this example our new promise takes a function that it runs that takes a resolve and reject parameter. What these are saying is "Oh yeah all good here's the result" or "Nope, sorry, no can do. Something happened and I can't fulfill this promise for you :(" These are the two outcomes when a promise is run and these can be nicely chained like so:
By putting .then() and .catch() after a promise we are able to set up more code to run when either the resolve or reject function is called from the promise, so whether it succeeds or fails / throws an error. With .then() we can pass in a function that takes in a single parameter which is the results from the resolved promise and use that data for whatever we need. Similarly .catch() takes a function that takes the error log as the first parameter and from there we can do whatever we want. We don't even have to use that error log, we can just use the catch as another form of conditional where if the previous promise fails then we do something else.
Here is where things start to get fun. If your .then() or .catch() call returns another promise, then you can keep chaining .then() and .catch() after it like so:
Ahh there we go, that looks a lot better than our callback hell from earlier. One thing to keep in mind, each .catch() call will catch errors from all the .then() calls above it so you only need one for each split in logic you want.
All of this how to use and set up promises is all good, but the real strength of where they lie is in all of the libraries that use promises to deal with asynchronous functionality. Some of the most widely used would be Axios to deal with sending requests to a server, and Sequelize to deal with searching a database, and getting comfortable with promises is the key to writing elegant and efficient code with these libraries. Now go forth and use this knowledge, I promise you it'll be useful.