A promise looks like this:
See the Pen GryKYG by Develop Intelligence ( @DevelopIntelligenceBoulder ) on CodePen .
Things to note:A promise is instantiated with a call to the Promise constructor Here, the promise is assigned to a promise variable A callback function is passed to the promise with the parameters resolve and reject Asynchronous code is executed within the promise’s callback function Good results are passed to the promise’s then method by calling resolve Bad results (and errors) are passed to the promise’s catch method by calling reject A callback is used in then to handle the good data A callback is used in catch to handle the bad data Examples
Here’s an example of a promise in action:
See the Pen RKxbOJ by Develop Intelligence ( @DevelopIntelligenceBoulder ) on CodePen .
Notice how the asynchronous setTimeout code is wrapped in the promise and it’s callback function, and how it returns a value 2 seconds after thetest function is called.The conditional logic within the promise/callback is used to determine whether resolve or reject gets called. The value resulting from the asynchronous code is passed to either then or catch through resolve or reject . If an error were to occur, it would also be passed to reject .
Additionally, worth noting is the common terminology used with promises:Before a promise receives a value, it is said to be pending Once a promise receives a value, if the value meets acceptance criteria, it’s fulfilled Once a value is received, if it doesn’t meet acceptance criteria, it’s rejected
Here’s one more example using AJAX :
See the Pen GryRBb by Develop Intelligence ( @DevelopIntelligenceBoulder ) on CodePen .
Notice how the AJAX code is wrapped in an instance of a promise. If everything goes well with the AJAX request, the returned value is resolved and sent to the promise’s then method for handling. If something goes wrong and the response comes back with something other than is intended or if there is an error, then that data will be picked up by the promises catch method, with the error data eventually being logged to the console. Promise, then, catch; it’s as easy as that.