Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Neil Bircumshaw
seal-mask
.a{fill-rule:evenodd;}techdegree
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Points

JavaScript promises.

Would I be wrong in comparing JavaScript promises to if statements as I feel like they work in a similar manner. So if the code is all good execute whatever, much like you would resolve with a promise. If not, which is where you would write "else", in promise you would write reject. I don't quite understand the "then" and "catch", is it these methods that make the code execute?

Are promises usually wrote within if and else statements, giving the code either the green or red light?

Thanks if anyone can clarify, the concept is a little tricky to grasp in my head.

1 Answer

Steven Parker
Steven Parker
229,644 Points

Yes, this concept is one of the trickier ones for sure. The promise itself is an object that represents some asynchronous process that may be currently still pending or has completed. The "then" and "catch" methods allow you to register fulfillment handlers.

There's more explanation on this MDN documenation page, along with a little demo which may help to make things clearer.

Neil Bircumshaw
seal-mask
.a{fill-rule:evenodd;}techdegree
Neil Bircumshaw
Full Stack JavaScript Techdegree Student 14,597 Points

So it's like an object in progress - this object either happens (resolves) and "then" you do something, or it fails for whatever reason (reject) and then you "catch" that failure. Is this right?

Is there any reason it's called a promise? Is it promising that it'll try and run the code for you?

Would it then be best to set up a promise every time you're making a request to the server?

Steven Parker
Steven Parker
229,644 Points

It sounds like you understand correctly. I don't really know the reason behind the word choice but I think your guess is as good as any. Or perhaps it is a "promise" to keep track of what happens to the process.

You can certainly keep track of asynchronous processes in other ways. I'm not sure I'd say a promise is the "best" way for all situations, but if used consistently it could lend an extra degree of coherence to your programs.