📎 Webclip
Write Better JavaScript with Promises
Promises make jQuery code easier to read because you can attach done, fail, and always handlers to the returned object, and the callbacks run in order. The article also shows that an API can return a promise instead of taking a handler, which makes it easier to pass the result around and transform it with then.
Reading notes#
- A callback example appends
data.textto the page after agetJSONrequest succeeds. - The promise version attaches
doneandfailhandlers directly to the object returned bygetJSON. - jQuery also provides
always, which runs whether the request succeeds or fails. - The callback order is preserved, with
donefirst,failsecond, andalwayslast. - A wrapper around the HipsterJesus API can return a promise from
htmlinstead of accepting a handler. thencan change the resolved value before passing it to the next handler in the chain.- AngularJS once allowed templates to bind directly to promises, and the article says this feature was later deprecated.
- Promises can be chained to build small methods such as
html,paragraphs, andsentences. - Multiple API calls become simpler with
$.when, which waits for both requests before running one handler.
