Making Promises
We started this chapter by showing how the Ajax methods in jQuery 1.5+ ($.ajax, $.get, and $.post) return Promises. But to really understand Promises, we need to make a few of our own.
Letâs give the user a prompt to hit either Y or N. The first thing weâll do is create an instance of $.Deferred that represents the userâs decision.
â | âvarâ promptDeferred = ânewâ $.Deferred(); |
â | promptDeferred.always(âfunctionâ(){ console.log(â'A choice was made:'â); }); |
â | promptDeferred.done(âfunctionâ(){ console.log(â'Starting game...'â); }); |
â | promptDeferred.fail(âfunctionâ(){ console.log(â'No game today.'â); }); |
(Note: always is available only in jQuery 1.6+.)
Youâre probably wondering ...
Get Async JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.