then accepts a second argument, which is invoked
when the Deferred
shifts to the rejected state.
To see this in action, add a second function argument (making sure to add
a comma between the two function arguments) to
formHandler.addSubmitHandler in main.js.
Inside of this function, show an alert with a simple
error message.
... formHandler.addSubmitHandler(function (data) { myTruck.createOrder.call(myTruck, data) .then(function () { checkList.addRow.call(checkList, data); }, function () { alert('Server unreachable. Try again later.'); } ); }); ...
At the top of main.js, misspell the server name so that Ajax requests fail. (This change will only be temporary, so you may want to simply cut a section out of the URL that you can paste back in later.)
(function (window) { 'use strict'; var FORM_SELECTOR = '[data-coffee-order="form"]'; var CHECKLIST_SELECTOR = '[data-coffee-order="checklist"]'; var SERVER_URL = 'http://coffeerun-v2-rest-api.herokuapp.com/api/coffeeorders/'; var App = window.App; ...
Save your changes, make sure browser-sync
is running,
and open CoffeeRun in the browser. Fill out the form.
You should see an alert pop up when you submit it (Figure 14.4).
Restore the SERVER_URL to http://coffeerun-v2-rest-api.herokuapp.com/api/coffeeorders/. You can also delete the function argument that shows the alert.
(function (window) { 'use strict'; var FORM_SELECTOR = '[data-coffee-order="form"]'; var CHECKLIST_SELECTOR = '[data-coffee-order="checklist"]'; var SERVER_URL = 'http://coffeerun-v2-rest-api.herokuapp.com/api/coffeeorders/'; ... formHandler.addSubmitHandler(function (data) { myTruck.createOrder.call(myTruck, data) .then(function () { checkList.addRow.call(checkList, data); },function () {alert('Server unreachable. Try again later.');}); }); ...
Using then to register callbacks maps
onto the way Promise
s work. If the Promise
changes
state to fulfilled, one set of callbacks is run. If the Promise
changes state to rejected, the other set of callbacks is run.
18.226.170.187