24
The Promise of jQuery Deferred 19th April 2013 — jQuery UK

The Promise of jQuery Deferred

Embed Size (px)

DESCRIPTION

The Promise JavaScript pattern is receiving quite a lot of attention recently as popular asynchronous pattern. This talk presents the way to understand the concept, how to learn using them step by step and how to design your software based on a real world example.

Citation preview

Page 1: The Promise of jQuery Deferred

The Promise ofjQuery Deferred

19th April 2013 — jQuery UK

Page 2: The Promise of jQuery Deferred

Tale Of A UK Job ApplicationAnd Pardon my French

1. Submitting an application form2. Being shortlisted3. Phone Interview4. Technical Interview5. Physical Interview6. Salary Negociation

Then, accept the contract and relocate or …

Page 3: The Promise of jQuery Deferred

Let's translate that inJavaScript…

Page 4: The Promise of jQuery Deferred

(function jobApplication(){ (function shortlist(data){ (function phoneInterview(){ (function technicalInterview(data){ (function physicalInterview(){ (function salaryNegociation(payload){ if (payload.job){ acceptContract() && relocate(); } else throw SyntaxError("Too bad…"); })({ job: "Software Engineer" }); })(); })({ script: "eval('alert(true);')" }); })(); })({ why: "I speak JavaScript!" });})();

Page 5: The Promise of jQuery Deferred

Badge Unlocked: Pyramid ofDoom!

Page 6: The Promise of jQuery Deferred

Promisification!

Page 7: The Promise of jQuery Deferred

.

var $job = $.Deferred();

$jobApplication .progress( updateApplicationState ) .done( acceptContract ) .done( relocate ) .fail( keepCalmAndDrinkWine );

$jobApplication .notify({ state: "shortlist" }) .notify({ state: "phone_interview" }) .notify({ state: "technical_interview" }) .notify({ state: "physical_interview" }) .notify({ state: "salary_negociation" });

$jobApplication.resolve({ job: "Software Engineer"});

See on JSBin

Page 8: The Promise of jQuery Deferred

Thomas ParisotFrontend / JavaScript Engineer

– –

BBC R&D IRFS

oncle-tom.net @oncletom github.com/oncletom

Page 9: The Promise of jQuery Deferred

Digging into jQuery.DeferredLearning to use Promises, the soft way.

Page 10: The Promise of jQuery Deferred

Consume the APIIn jQuery 1.8+: $.ajax, $.animate, $('<selector>')

var $deferred = $.post('/cheese', { name: "Livarot"});

$deferred .done( syncLocalStorage ) .done( updateUI ) .fail( displayError ) .always( logNetworkResponse );

Page 11: The Promise of jQuery Deferred

Create your first Deferred

.

function getDelayedUserInput(){ var $deferred = $.Deferred();

setTimeout(function(){ $deferred.resolve(prompt("Anything to say?")); }, 1000);

return $deferred;}

$('input').on('click', function(e){ getDelayedUserInput().done(function(user_input){ $(e.target).val(user_input); });});

See on JSBin

Page 12: The Promise of jQuery Deferred

Deal with race conditionworkflows

then() enables data filtering.when() is a done() for multiple promises.

$.when( $.getJSON('/page/1'), $.getJSON('/page/2') ) .then(function(page1_data, page2_data){ return page1_data.concat(page2_data); }) .done( displayCombinedData ) .fail( displayError );

Page 13: The Promise of jQuery Deferred

Sharing safely your DeferredjQuery.Deferred vs. Deferred.promise().

.

var $deferred = $.Deferred();var $promise = $deferred.promise();

$promise.done(function(value){ console.log("Oh my "+value);});

// $promise is read-only$promise.resolve("gosh");

// will log 'Oh my head'$deferred.resolve("head");

See on JSBin

Page 14: The Promise of jQuery Deferred

Improving our first Deferred

.

function getDelayedUserInput(){ var $deferred = $.Deferred();

setTimeout(function(){ $deferred.resolve(prompt("Anything to say?")); }, 1000);

return $deferred.promise(); // now safe}

$('input').on('click', function(e){ getDelayedUserInput().done(function(user_input){ $(e.target).val(user_input); });});

See on JSBin

Page 15: The Promise of jQuery Deferred

Tale of a country relocationLet's use another real life example (that's still better than Hello world examples).

1. opening a bank account2. finding a new place to live3. request a NINo4. ask for a debit card

And hope for an on-time payday to finally live like a newsettler!

Page 16: The Promise of jQuery Deferred

Opening a bank accountfunction requestBankAccount(job, postal_address){ var $deferred;

// expect an 'account' object to be resolved $deferred = $.post('http://bank.com/account', { job: job, address: postal_address });

return $deferred.promise();}

Page 17: The Promise of jQuery Deferred

Assembling the workflowLet's assume we have a $job promise available in the scope.

var $address, $account, $NINo, $debitCard;

$address = requestAppartment(job);

$.when($job, $address).done(function(job, address){ $account = requestBankAccount(job, address); $NINo = requestNINo(job, address);

$account.done(function(account){ $debitCard = requestDebitCard(account, address); });});

Page 18: The Promise of jQuery Deferred

Killing the FUDThe Internet told me:

the Promises are everythingthe Promises are Evil

Page 19: The Promise of jQuery Deferred

Callback vs. Promise vs.Event

Callbacks are for easy and simple uses.

Events are for vertical code expansion.

nodes.value(function(item){ return item.service_id;});

MyModule.prototype.init = function init(view){ view.$submit.on('click', this.handleSubmit); view.$document.on('click keyup', this.logEvent);};

Page 20: The Promise of jQuery Deferred

When to use them?Some considerations to think about to know when to use

Promises.

simplifying a workflow contractflattening code nestingundeterminate duration async taskcoordinating multiple async tasks

tl;dr: modularize chained tasks.

Page 21: The Promise of jQuery Deferred

jQuery Deferred is notPromise/A+ compliant

Who cares? As long as it helps you to:

simplify your codekeep your code maintainable (for you and your peers)

Page 22: The Promise of jQuery Deferred

Remember kidsPatterns and tools help to solve problems.

You solve the problems.

FUD solves nothing.

Page 24: The Promise of jQuery Deferred

Thanks everybodyHave a question? Come talk / tweet / email to me.