Skip to Main Content
Async JavaScript
book

Async JavaScript

by Trevor Burnham
November 2012
Intermediate to advanced content levelIntermediate to advanced
106 pages
2h 20m
English
Pragmatic Bookshelf
Content preview from Async JavaScript

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 why I created an instance of Deferred when this section ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Modern Asynchronous JavaScript

Modern Asynchronous JavaScript

Faraz K. Kelhini
Learn TypeScript 3 by Building Web Applications

Learn TypeScript 3 by Building Web Applications

Sebastien Dubois, Alexis Georges

Publisher Resources

ISBN: 9781941222782Errata