Upload
thomas-parisot
View
3.384
Download
0
Tags:
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
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 …
Let's translate that inJavaScript…
(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!" });})();
Badge Unlocked: Pyramid ofDoom!
Promisification!
.
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
Thomas ParisotFrontend / JavaScript Engineer
– –
BBC R&D IRFS
oncle-tom.net @oncletom github.com/oncletom
Digging into jQuery.DeferredLearning to use Promises, the soft way.
Consume the APIIn jQuery 1.8+: $.ajax, $.animate, $('<selector>')
var $deferred = $.post('/cheese', { name: "Livarot"});
$deferred .done( syncLocalStorage ) .done( updateUI ) .fail( displayError ) .always( logNetworkResponse );
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
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 );
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
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
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!
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();}
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); });});
Killing the FUDThe Internet told me:
the Promises are everythingthe Promises are Evil
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);};
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.
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)
Remember kidsPatterns and tools help to solve problems.
You solve the problems.
FUD solves nothing.
To infinity and beyond!
Libraries: , ,
jQuery Deferred APICommonJS Promise/A+ECMAScript PromisesDOM Future
async ff q
Thanks everybodyHave a question? Come talk / tweet / email to me.