A Promise object is created using new keyword and passing an executor function which contains the asynchronous code to be executed. The function takes two handlers, resolve and reject, as arguments which are called by the asynchronous code when it completes successfully or fails due to an error. A Promise can be in one of the three states-
Pending state - This is the initial state, indicating that the asynchronous action is not yet complete.
Fulfilled state - The asynchronous code completed successfully
Rejected state - The asynchronous code failed.
Because the promise is executed asynchronously we do not know when the success or error will be reported. To get the result we need to use the Promise.then() function. then() takes two function callbacks, one for success and one for failure. The success callback is called when the promise is fulfilled and the failure callback is called when the promise is rejected. The data passed to resolve or reject are passed to these callbacks.
The page displays a number and provides two buttons to select if the number is even or odd. When a button is clicked userChoice() function is called with the string 'even' or 'odd'. In userChoice we are creating a Promise object. The asynchronous code in the promise computes whether the number displayed is even or odd. If the user has made the right selection then the promise is fulfilled otherwise the promise is rejected. After creating the promise the number displayed is changed through generateRandomNumber(). In promise.then() the success callback gets the "Right Answer." message which is displayed in a pop-up. Similarly the error callback gets a "Wrong Answer." message and displays it in a pop-up. Since the promise is asynchronous, the new number is already displayed on the page even before the pop-up is closed.