Promises ...what?

So I’ve decided (reluctantly, mind you) to keep going w/ practicing JS basics through Udemy and CodeCademy. I’ve gotten to combining promise and .then() and need some help getting a better explanation on those. I know a bit of how they operate, but beyond that, I’m confused why and when they’re used.

Thanks.

Promises are a cleaner way to handle asynchronous behavior. The older method was callbacks, but that can get messy. With a Promise, you can tell it to do something asynchronous and tell it to “then” do something new. You can create your own Promises (which a lot of the material focuses on) of you can use Promises that are returned by other things, like fetch.

It’s going to be a confusing subject. Just take it on faith that this is important and will make sense eventually. Just keep plugging away. Read some articles, watch some videos, write some code, etc.

1 Like

I appreciate the timely response and advice. I think whats hanging me up currently, is understanding (fully) what asynchronous behavior. First and foremost.

Synchronous behavior means something that is going to happen right now and JS is going to wait for it. Asynchronous means that JS will not wait for it. This is really important on the internet because a lot of the time you are talking to other servers. If you request a file, how long will it take? 1/1000th of a second? 10 seconds? 10 years?

Many languages have difficulty handling this but since JS was built for the internet, it was built into the language. If I need to fetch data from a database, JS does not wait for it, it just keeps going onto the next line. But there has to be some way to handle the data when it gets back. The old way was to pass a callback function - when the data gets back, feed it to this function and it will know what to do with it. That gets messy. Promises make it a little cleaner, but still it’s a similar concept - when the data gets back, feed it to the function in the then block. One of the advantages of Promises is that you can chain then blocks together (with callbacks they’d have to be nested, which can get confusing.) Later you’ll learn about async/await which uses Promises but makes them even easier and cleaner to read.

Just work with it. Understanding will come.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.