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...'​); });​function​(){ console.log(​'No game today.'​); });

(Note: always is available only in jQuery 1.6+.)

You’re probably wondering why I created an instance of Deferred when this section ...

Get Async JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.