SlideShare a Scribd company logo
1 of 25
Download to read offline
Threading in Javascript
or How I Came to Love Multi-Threading in JavaScript Clients
Jonathan Baker
Director, Developer Relations
SAP Labs, LLC
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 2
What’s up for today?
JavaScript by spec
Handling long operations
Ÿ Timeouts (or yield)
Ÿ Workers
Ÿ Promises
The shared data conundrum
Ÿ Loading data in separate AJAX calls
Ÿ The problems with partial data - lookups?
Final thoughts
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 3
JavaScript by spec
8.3 Execution Contexts
An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript
implementation. At any point in time, there is at most one execution context that is actually executing code. This is known as
the running execution context.
The execution context stack is used to track execution contexts. The running execution context is always the top element of this
stack. A new execution context is created whenever control is transferred from the executable code associated with the
currently running execution contextto executable code that is not associated with that execution context. The newly created
execution context is pushed onto the stack and becomes the running execution context.
Evaluation of code by the running execution context may be suspended at various points defined
within this specification.
ECMA Script Specification 2017 – Draft ECMA 262
https://tc39.github.io/ecma262/#sec-execution-contexts
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 4
And now for a 90 second op-ed…
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 5
Looooonnnnngg operations
My pet peeve – the unintended long operation
You wrote something that shouldn’t be long, but now is – and it’s interrupting the user
Proper design from the beginning – these should be in your toolbox
Ÿ setTimeout() and setInterval()
Ÿ Workers()
Ÿ Promises()
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 6
Cost analysis
Finding a specific user: Average Time = n/2, worst case is n.
10,000 users cached
100 rows of bets
Average time: 10,000 * 100 / 2 = 500,000 checks
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 7
setTimeout() and setInterval()
timerId = setTimeout( function(), time_in_ms );
Called a single time, with a delay of “time_in_ms” before being put on the event queue.
timerId = setInterval( function(), time_in_ms );
Called multiple times. An event will be added to the queue every ”time_in_ms”
Quick Recap
Ÿ Full access to the global scope and DOM
Ÿ Runs in the same thread as the GUI (interrupts only)
Ÿ setTimeout(0) is essentially a process yield()
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 8
Workers()
Workers are the most basic of asynchronous handlers
Ÿ They run in a separate thread
Ÿ Independent context, communicates by messaging
var w = new worker(“script path on server”);
w.onmessage = function(event) { yourData = event.data };
w.onerror = function(error) { . . . };
w.postMessage(sent_data);
w.terminate();
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 9
Promises()
Promises are the next generation of asynchronous support
Finalized in 2013 (and in beta for a while)
New mechanism for providing asynchronous calls with response patterns
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 10
Promises – how do they work?
When creating asynchronous code, the response mechanism matters.
Main Code
var promise =
new Promise(function(resolve,reject){}
);
promise.then( function(result){} ,
function(error){} );
Promise Object
(inside, running asynchronously)
function(resolve,reject) {
. . .
if( success ) {
resolve(data);
} else {
reject( Error(xxx) );
}
}
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 11
Chaining Promises
var getData = function(url) {
return new Promise(. . .);
}
getData(url1).then( function(data1) {
return getData(data1.url2);
}).then( function(data2) {
// display html with data2
}).catch( function(error) {
// error dialog!!
}).then( function() {
$(’#spinner').hide();
}
var getData = function(url) {
return new Promise(. . .);
}
try {
getData(url1);
getData(url2);
// display html with data2
}
catch (e) {
// error dialog!!
}
$(’#spinner’).hide();
Chain Promises? Use a function call (the stack will hold the value for the promise)
Promises in parallel? Promise.all(arrayOfPromises).then( . . . );
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 12
Moving on to data
Loading Data in separate AJAX calls
The problems with partial data
Angular examples
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 13
Simple cross-referencing data model
Let’s consider data loaded from a server for a simple (if quasi-legal) application:
Horse BET Person
GET /horses GET /bets GET /people
[ id: 1,
name: Nyquist,
odds: 1.65 ]
[ id: 1,
horse: 1,
person: 42,
amount: 25.00,
position: win ]
[ id: 42,
name: Zaphod ]
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 14
Loading linked data effectively
If we want to load the cross references, we have many options
In this example:
Ÿ Horses is a small list – load it immediately
Ÿ Person is a huge list – load dynamically as needed (caching?)
Ÿ Bets – load a page at a time (depending on what the user wants to see)
Horse BET Person
GET /horses GET /bets/subsetX GET /people/{id}
15© 2016 SAP SE or an SAP affiliate company. All rights reserved.
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 16
Behind the scenes
Horses load
Bets load
Ÿ If horses are already loaded, then bind horses to
horseId in bets (Angular filter), if not, wait for them.
Ÿ After bets loads, we know which Users we want.
Load them
Users load
Ÿ After users has loaded, bind to bets
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 17
Do we load the users all at once, or one at a time?
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 18
Lets load the bets
$http.get(‘/bets’).then( function(resp) {
$scope.betsList = resp.data.map( function(val) {
return { id : Number(val.id),
accountId : Number(val.accountId),
horseId : Number(val.horseId),
account : undefined,
horse : undefined,
...};
if ($scope.horseList) { //map horses to bets }
for(var i=0, I < $scope.betsList.length ; i++ ) {
$http.get(’/account/’+$scope.betsList[i].accountId).then( function(resp){
// Take the response, find the bet, and attach the account
});
};
});
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 19
Where are the problems?
$http.get(‘/bets’).then( function(resp) {
$scope.betsList = resp.data.map( function(val) {
return { id : Number(val.id),
accountId : Number(val.accountId),
horseId : Number(val.horseId),
account : undefined,
horse : undefined,
...};
if ($scope.horseList) { //map horses to bets }
for(var i=0, i < $scope.betsList.length ; i++ ) {
$http.get(’/account/’+$scope.betsList[i].accountId).then( function(resp){
// Take the response, find the bet, and attach the account
});
};
});
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 20
Cost analysis
If we start to cache data, things get interesting
Finding a specific user: Average Time = n/2, worst case is n.
10,000 users cached
100 rows of bets
Average time: 10,000 * 100 / 2 = 500,000 checks
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 21
Using Promises to move the processing
function getBets() {
var p1 = Promise.resolve( $.get( "/data/main/bets" ) );
var p2 = p1.then( function( response ) {
return convertBetsListFromServer( response );
})
p2.then(function(finalBetsData) {
$scope.betsList = finalBetsData;
$scope.$apply();
// Now, start up a bunch of promises to get each individual record
bindAccountsToBets( finalBetsData );
})
}
(We would handle error conditions, if the screen resolution would let us!)
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 22
Making the Promises even smarter
var p1 = new Promise( // resolve bets );
var p2 = new Promise( // resolve horses );
function linkHorsesToBets( horses, bets ) {
return new Promise( function(resolve,reject) {
for(var i=0, i < bets.length ; i++ ) {
bets.horse = $.grep(horses, function(e){ return e.id == bets[i].horseId; });
resolve( bets );
};
});
}
Promise.all( [ p1, p2 ] ).then( function( values ){
var bets = values[0];
var horses = values[1];
linkHorsesToBets( horses, bets ).then( function(result){ $scope.bets = result; });
});
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 23
Imagine a smarter model
// If we know a column has a lookup, we could preset it
Model.setColumnLookup( columnOrigin, columnForData, column_lookup_function() )
// What if we want to wait for another system?
// Promise.all([a,b,...])
Model.bindAfterLoad( dataA, dataB, bind_function() )
// We could even set up a caching system for some data
Model.cacheDataset()
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 24
Bringing it all together
Identify what belongs in the user thread
Ÿ Data should be loaded and ready to go!
Ÿ Look for long running loops and processing
Understand the toolset
Ÿ setTimeout()
Ÿ Worker()
Ÿ Promise()
Use the tools to create code that is both user-responsive and hard working
© 2016 SAP SE or an SAP affiliate company. All rights reserved. 25
Hit PAUSE, and discuss
Questions?

More Related Content

What's hot

Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Eyal Vardi
 
PHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the testsPHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the testsMichelangelo van Dam
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Konstantin Kudryashov
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive? Tomasz Kowalczewski
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Eyal Vardi
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringCary Millsap
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web ModuleMorgan Cheng
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Eyal Vardi
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmineRubyc Slides
 
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached georgepenkov
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in ApexJeffrey Kemp
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Eyal Vardi
 
AngularJS Tips&Tricks
AngularJS Tips&TricksAngularJS Tips&Tricks
AngularJS Tips&TricksPetr Bela
 

What's hot (20)

Second Level Cache in JPA Explained
Second Level Cache in JPA ExplainedSecond Level Cache in JPA Explained
Second Level Cache in JPA Explained
 
Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0Proxies in ECMAScript 6.0
Proxies in ECMAScript 6.0
 
PHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the testsPHPUnit Episode iv.iii: Return of the tests
PHPUnit Episode iv.iii: Return of the tests
 
Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015Min-Maxing Software Costs - Laracon EU 2015
Min-Maxing Software Costs - Laracon EU 2015
 
Is writing performant code too expensive?
Is writing performant code too expensive? Is writing performant code too expensive?
Is writing performant code too expensive?
 
Modules in ECMAScript 6.0
Modules in ECMAScript 6.0Modules in ECMAScript 6.0
Modules in ECMAScript 6.0
 
Innovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and MonitoringInnovative Specifications for Better Performance Logging and Monitoring
Innovative Specifications for Better Performance Logging and Monitoring
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Rxjs marble-testing
Rxjs marble-testingRxjs marble-testing
Rxjs marble-testing
 
Thinking Beyond ORM in JPA
Thinking Beyond ORM in JPAThinking Beyond ORM in JPA
Thinking Beyond ORM in JPA
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Angular mix chrisnoring
Angular mix chrisnoringAngular mix chrisnoring
Angular mix chrisnoring
 
Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
 
JavaFX Pitfalls
JavaFX PitfallsJavaFX Pitfalls
JavaFX Pitfalls
 
Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0Iterators & Generators in ECMAScript 6.0
Iterators & Generators in ECMAScript 6.0
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
 
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached
Saving The World From Guaranteed APOCALYPSE* Using Varnish and Memcached
 
Building Maintainable Applications in Apex
Building Maintainable Applications in ApexBuilding Maintainable Applications in Apex
Building Maintainable Applications in Apex
 
Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0Scope & Functions in ECMAScript 6.0
Scope & Functions in ECMAScript 6.0
 
AngularJS Tips&Tricks
AngularJS Tips&TricksAngularJS Tips&Tricks
AngularJS Tips&Tricks
 

Viewers also liked

How a Top Physician Group Migrated to the Cloud with PBCS
How a Top Physician Group Migrated to the Cloud with PBCSHow a Top Physician Group Migrated to the Cloud with PBCS
How a Top Physician Group Migrated to the Cloud with PBCSPerficient, Inc.
 
How to launch web dynpro abap and sap gui for html application types from the...
How to launch web dynpro abap and sap gui for html application types from the...How to launch web dynpro abap and sap gui for html application types from the...
How to launch web dynpro abap and sap gui for html application types from the...Herman Syah
 
Selling E-Commerce to Your Leadership
Selling E-Commerce to Your LeadershipSelling E-Commerce to Your Leadership
Selling E-Commerce to Your LeadershipSAP Ariba
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Learning salesforce-mobile-way
Learning salesforce-mobile-wayLearning salesforce-mobile-way
Learning salesforce-mobile-wayAbhinav Gupta
 
NoSQL Deepdive - with Informix NoSQL. IOD 2013
NoSQL Deepdive - with Informix NoSQL. IOD 2013NoSQL Deepdive - with Informix NoSQL. IOD 2013
NoSQL Deepdive - with Informix NoSQL. IOD 2013Keshav Murthy
 
Best Practices in Catalog Strategies
Best Practices in Catalog StrategiesBest Practices in Catalog Strategies
Best Practices in Catalog StrategiesSAP Ariba
 
SAP TechEd 2016 UX261 sap_screen_personas_hands-on
SAP TechEd 2016 UX261 sap_screen_personas_hands-onSAP TechEd 2016 UX261 sap_screen_personas_hands-on
SAP TechEd 2016 UX261 sap_screen_personas_hands-onPeter Spielvogel
 
Industry Cloud Forum 2015 - Emergence Capital Keynote
Industry Cloud Forum 2015 - Emergence Capital KeynoteIndustry Cloud Forum 2015 - Emergence Capital Keynote
Industry Cloud Forum 2015 - Emergence Capital KeynoteEmergence Capital
 
E business applications
E business applicationsE business applications
E business applicationsRaj vardhan
 
50 Most Influential Content Marketers
50 Most Influential Content Marketers50 Most Influential Content Marketers
50 Most Influential Content MarketersNewsCred
 
Principles of microservices ndc oslo
Principles of microservices   ndc osloPrinciples of microservices   ndc oslo
Principles of microservices ndc osloSam Newman
 
25 MarTech Tools Used By Demand Marketing Game Changers
25 MarTech Tools Used By Demand Marketing Game Changers25 MarTech Tools Used By Demand Marketing Game Changers
25 MarTech Tools Used By Demand Marketing Game ChangersIntegrate
 
MicroServices at Netflix - challenges of scale
MicroServices at Netflix - challenges of scaleMicroServices at Netflix - challenges of scale
MicroServices at Netflix - challenges of scaleSudhir Tonse
 
Network for the Large-scale Hadoop cluster at Yahoo! JAPAN
Network for the Large-scale Hadoop cluster at Yahoo! JAPANNetwork for the Large-scale Hadoop cluster at Yahoo! JAPAN
Network for the Large-scale Hadoop cluster at Yahoo! JAPANDataWorks Summit/Hadoop Summit
 
Nestle final project
Nestle final projectNestle final project
Nestle final projectwaheeducp
 
The Brand Gap
The Brand GapThe Brand Gap
The Brand Gapcoolstuff
 

Viewers also liked (18)

How a Top Physician Group Migrated to the Cloud with PBCS
How a Top Physician Group Migrated to the Cloud with PBCSHow a Top Physician Group Migrated to the Cloud with PBCS
How a Top Physician Group Migrated to the Cloud with PBCS
 
How to launch web dynpro abap and sap gui for html application types from the...
How to launch web dynpro abap and sap gui for html application types from the...How to launch web dynpro abap and sap gui for html application types from the...
How to launch web dynpro abap and sap gui for html application types from the...
 
Selling E-Commerce to Your Leadership
Selling E-Commerce to Your LeadershipSelling E-Commerce to Your Leadership
Selling E-Commerce to Your Leadership
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Learning salesforce-mobile-way
Learning salesforce-mobile-wayLearning salesforce-mobile-way
Learning salesforce-mobile-way
 
NoSQL Deepdive - with Informix NoSQL. IOD 2013
NoSQL Deepdive - with Informix NoSQL. IOD 2013NoSQL Deepdive - with Informix NoSQL. IOD 2013
NoSQL Deepdive - with Informix NoSQL. IOD 2013
 
The Workforce 2020
The Workforce 2020The Workforce 2020
The Workforce 2020
 
Best Practices in Catalog Strategies
Best Practices in Catalog StrategiesBest Practices in Catalog Strategies
Best Practices in Catalog Strategies
 
SAP TechEd 2016 UX261 sap_screen_personas_hands-on
SAP TechEd 2016 UX261 sap_screen_personas_hands-onSAP TechEd 2016 UX261 sap_screen_personas_hands-on
SAP TechEd 2016 UX261 sap_screen_personas_hands-on
 
Industry Cloud Forum 2015 - Emergence Capital Keynote
Industry Cloud Forum 2015 - Emergence Capital KeynoteIndustry Cloud Forum 2015 - Emergence Capital Keynote
Industry Cloud Forum 2015 - Emergence Capital Keynote
 
E business applications
E business applicationsE business applications
E business applications
 
50 Most Influential Content Marketers
50 Most Influential Content Marketers50 Most Influential Content Marketers
50 Most Influential Content Marketers
 
Principles of microservices ndc oslo
Principles of microservices   ndc osloPrinciples of microservices   ndc oslo
Principles of microservices ndc oslo
 
25 MarTech Tools Used By Demand Marketing Game Changers
25 MarTech Tools Used By Demand Marketing Game Changers25 MarTech Tools Used By Demand Marketing Game Changers
25 MarTech Tools Used By Demand Marketing Game Changers
 
MicroServices at Netflix - challenges of scale
MicroServices at Netflix - challenges of scaleMicroServices at Netflix - challenges of scale
MicroServices at Netflix - challenges of scale
 
Network for the Large-scale Hadoop cluster at Yahoo! JAPAN
Network for the Large-scale Hadoop cluster at Yahoo! JAPANNetwork for the Large-scale Hadoop cluster at Yahoo! JAPAN
Network for the Large-scale Hadoop cluster at Yahoo! JAPAN
 
Nestle final project
Nestle final projectNestle final project
Nestle final project
 
The Brand Gap
The Brand GapThe Brand Gap
The Brand Gap
 

Similar to GlueCon 2016 - Threading in JavaScript

Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerNic Raboy
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Codemotion
 
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)Maximilian Lenkeit
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Tom Diederich
 
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...Achim D. Brucker
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenJoshua Long
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020Matt Raible
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the CloudWesley Beary
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworksEric Guo
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesLindsay Holmwood
 
Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Vendic Magento, PWA & Marketing
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)Wesley Beary
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012hwilming
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous JavascriptGarrett Welson
 
Introduction to Joins in Structured Streaming
Introduction to Joins in Structured StreamingIntroduction to Joins in Structured Streaming
Introduction to Joins in Structured StreamingKnoldus Inc.
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless BallerinaBallerina
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...GITS Indonesia
 

Similar to GlueCon 2016 - Threading in JavaScript (20)

Quick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase ServerQuick and Easy Development with Node.js and Couchbase Server
Quick and Easy Development with Node.js and Couchbase Server
 
Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016Promises are so passé - Tim Perry - Codemotion Milan 2016
Promises are so passé - Tim Perry - Codemotion Milan 2016
 
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)
Building Custom Controls to Visualize Data (UI5Con 2016 Frankfurt)
 
Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)Ingesting streaming data for analysis in apache ignite (stream sets theme)
Ingesting streaming data for analysis in apache ignite (stream sets theme)
 
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...
A Collection of Real World (JavaScript) Security Problems: Examples from 2 1/...
 
Spring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in HeavenSpring and Cloud Foundry; a Marriage Made in Heaven
Spring and Cloud Foundry; a Marriage Made in Heaven
 
Amazon elastic map reduce
Amazon elastic map reduceAmazon elastic map reduce
Amazon elastic map reduce
 
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 202010 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
10 Excellent Ways to Secure Spring Boot Applications - Okta Webinar 2020
 
fog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloudfog or: How I Learned to Stop Worrying and Love the Cloud
fog or: How I Learned to Stop Worrying and Love the Cloud
 
Rails 6 frontend frameworks
Rails 6 frontend frameworksRails 6 frontend frameworks
Rails 6 frontend frameworks
 
Burn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websitesBurn down the silos! Helping dev and ops gel on high availability websites
Burn down the silos! Helping dev and ops gel on high availability websites
 
Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)Running Vue Storefront in production (PWA Magento webshop)
Running Vue Storefront in production (PWA Magento webshop)
 
Parse Advanced
Parse AdvancedParse Advanced
Parse Advanced
 
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
fog or: How I Learned to Stop Worrying and Love the Cloud (OpenStack Edition)
 
Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012Integrating SAP the Java EE Way - JBoss One Day talk 2012
Integrating SAP the Java EE Way - JBoss One Day talk 2012
 
Intro to Asynchronous Javascript
Intro to Asynchronous JavascriptIntro to Asynchronous Javascript
Intro to Asynchronous Javascript
 
Introduction to Joins in Structured Streaming
Introduction to Joins in Structured StreamingIntroduction to Joins in Structured Streaming
Introduction to Joins in Structured Streaming
 
Serverless Ballerina
Serverless BallerinaServerless Ballerina
Serverless Ballerina
 
ES6: The Awesome Parts
ES6: The Awesome PartsES6: The Awesome Parts
ES6: The Awesome Parts
 
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
Fundamental Node.js (Workshop bersama Front-end Developer GITS Indonesia, War...
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptkotipi9215
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...aditisharan08
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio, Inc.
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyFrank van der Linden
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 

Recently uploaded (20)

Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
chapter--4-software-project-planning.ppt
chapter--4-software-project-planning.pptchapter--4-software-project-planning.ppt
chapter--4-software-project-planning.ppt
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...Unit 1.1 Excite Part 1, class 9, cbse...
Unit 1.1 Excite Part 1, class 9, cbse...
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed DataAlluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
Alluxio Monthly Webinar | Cloud-Native Model Training on Distributed Data
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
Engage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The UglyEngage Usergroup 2024 - The Good The Bad_The Ugly
Engage Usergroup 2024 - The Good The Bad_The Ugly
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 

GlueCon 2016 - Threading in JavaScript

  • 1. Threading in Javascript or How I Came to Love Multi-Threading in JavaScript Clients Jonathan Baker Director, Developer Relations SAP Labs, LLC
  • 2. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 2 What’s up for today? JavaScript by spec Handling long operations Ÿ Timeouts (or yield) Ÿ Workers Ÿ Promises The shared data conundrum Ÿ Loading data in separate AJAX calls Ÿ The problems with partial data - lookups? Final thoughts
  • 3. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 3 JavaScript by spec 8.3 Execution Contexts An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation. At any point in time, there is at most one execution context that is actually executing code. This is known as the running execution context. The execution context stack is used to track execution contexts. The running execution context is always the top element of this stack. A new execution context is created whenever control is transferred from the executable code associated with the currently running execution contextto executable code that is not associated with that execution context. The newly created execution context is pushed onto the stack and becomes the running execution context. Evaluation of code by the running execution context may be suspended at various points defined within this specification. ECMA Script Specification 2017 – Draft ECMA 262 https://tc39.github.io/ecma262/#sec-execution-contexts
  • 4. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 4 And now for a 90 second op-ed…
  • 5. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 5 Looooonnnnngg operations My pet peeve – the unintended long operation You wrote something that shouldn’t be long, but now is – and it’s interrupting the user Proper design from the beginning – these should be in your toolbox Ÿ setTimeout() and setInterval() Ÿ Workers() Ÿ Promises()
  • 6. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 6 Cost analysis Finding a specific user: Average Time = n/2, worst case is n. 10,000 users cached 100 rows of bets Average time: 10,000 * 100 / 2 = 500,000 checks
  • 7. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 7 setTimeout() and setInterval() timerId = setTimeout( function(), time_in_ms ); Called a single time, with a delay of “time_in_ms” before being put on the event queue. timerId = setInterval( function(), time_in_ms ); Called multiple times. An event will be added to the queue every ”time_in_ms” Quick Recap Ÿ Full access to the global scope and DOM Ÿ Runs in the same thread as the GUI (interrupts only) Ÿ setTimeout(0) is essentially a process yield()
  • 8. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 8 Workers() Workers are the most basic of asynchronous handlers Ÿ They run in a separate thread Ÿ Independent context, communicates by messaging var w = new worker(“script path on server”); w.onmessage = function(event) { yourData = event.data }; w.onerror = function(error) { . . . }; w.postMessage(sent_data); w.terminate();
  • 9. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 9 Promises() Promises are the next generation of asynchronous support Finalized in 2013 (and in beta for a while) New mechanism for providing asynchronous calls with response patterns
  • 10. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 10 Promises – how do they work? When creating asynchronous code, the response mechanism matters. Main Code var promise = new Promise(function(resolve,reject){} ); promise.then( function(result){} , function(error){} ); Promise Object (inside, running asynchronously) function(resolve,reject) { . . . if( success ) { resolve(data); } else { reject( Error(xxx) ); } }
  • 11. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 11 Chaining Promises var getData = function(url) { return new Promise(. . .); } getData(url1).then( function(data1) { return getData(data1.url2); }).then( function(data2) { // display html with data2 }).catch( function(error) { // error dialog!! }).then( function() { $(’#spinner').hide(); } var getData = function(url) { return new Promise(. . .); } try { getData(url1); getData(url2); // display html with data2 } catch (e) { // error dialog!! } $(’#spinner’).hide(); Chain Promises? Use a function call (the stack will hold the value for the promise) Promises in parallel? Promise.all(arrayOfPromises).then( . . . );
  • 12. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 12 Moving on to data Loading Data in separate AJAX calls The problems with partial data Angular examples
  • 13. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 13 Simple cross-referencing data model Let’s consider data loaded from a server for a simple (if quasi-legal) application: Horse BET Person GET /horses GET /bets GET /people [ id: 1, name: Nyquist, odds: 1.65 ] [ id: 1, horse: 1, person: 42, amount: 25.00, position: win ] [ id: 42, name: Zaphod ]
  • 14. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 14 Loading linked data effectively If we want to load the cross references, we have many options In this example: Ÿ Horses is a small list – load it immediately Ÿ Person is a huge list – load dynamically as needed (caching?) Ÿ Bets – load a page at a time (depending on what the user wants to see) Horse BET Person GET /horses GET /bets/subsetX GET /people/{id}
  • 15. 15© 2016 SAP SE or an SAP affiliate company. All rights reserved.
  • 16. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 16 Behind the scenes Horses load Bets load Ÿ If horses are already loaded, then bind horses to horseId in bets (Angular filter), if not, wait for them. Ÿ After bets loads, we know which Users we want. Load them Users load Ÿ After users has loaded, bind to bets
  • 17. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 17 Do we load the users all at once, or one at a time?
  • 18. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 18 Lets load the bets $http.get(‘/bets’).then( function(resp) { $scope.betsList = resp.data.map( function(val) { return { id : Number(val.id), accountId : Number(val.accountId), horseId : Number(val.horseId), account : undefined, horse : undefined, ...}; if ($scope.horseList) { //map horses to bets } for(var i=0, I < $scope.betsList.length ; i++ ) { $http.get(’/account/’+$scope.betsList[i].accountId).then( function(resp){ // Take the response, find the bet, and attach the account }); }; });
  • 19. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 19 Where are the problems? $http.get(‘/bets’).then( function(resp) { $scope.betsList = resp.data.map( function(val) { return { id : Number(val.id), accountId : Number(val.accountId), horseId : Number(val.horseId), account : undefined, horse : undefined, ...}; if ($scope.horseList) { //map horses to bets } for(var i=0, i < $scope.betsList.length ; i++ ) { $http.get(’/account/’+$scope.betsList[i].accountId).then( function(resp){ // Take the response, find the bet, and attach the account }); }; });
  • 20. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 20 Cost analysis If we start to cache data, things get interesting Finding a specific user: Average Time = n/2, worst case is n. 10,000 users cached 100 rows of bets Average time: 10,000 * 100 / 2 = 500,000 checks
  • 21. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 21 Using Promises to move the processing function getBets() { var p1 = Promise.resolve( $.get( "/data/main/bets" ) ); var p2 = p1.then( function( response ) { return convertBetsListFromServer( response ); }) p2.then(function(finalBetsData) { $scope.betsList = finalBetsData; $scope.$apply(); // Now, start up a bunch of promises to get each individual record bindAccountsToBets( finalBetsData ); }) } (We would handle error conditions, if the screen resolution would let us!)
  • 22. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 22 Making the Promises even smarter var p1 = new Promise( // resolve bets ); var p2 = new Promise( // resolve horses ); function linkHorsesToBets( horses, bets ) { return new Promise( function(resolve,reject) { for(var i=0, i < bets.length ; i++ ) { bets.horse = $.grep(horses, function(e){ return e.id == bets[i].horseId; }); resolve( bets ); }; }); } Promise.all( [ p1, p2 ] ).then( function( values ){ var bets = values[0]; var horses = values[1]; linkHorsesToBets( horses, bets ).then( function(result){ $scope.bets = result; }); });
  • 23. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 23 Imagine a smarter model // If we know a column has a lookup, we could preset it Model.setColumnLookup( columnOrigin, columnForData, column_lookup_function() ) // What if we want to wait for another system? // Promise.all([a,b,...]) Model.bindAfterLoad( dataA, dataB, bind_function() ) // We could even set up a caching system for some data Model.cacheDataset()
  • 24. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 24 Bringing it all together Identify what belongs in the user thread Ÿ Data should be loaded and ready to go! Ÿ Look for long running loops and processing Understand the toolset Ÿ setTimeout() Ÿ Worker() Ÿ Promise() Use the tools to create code that is both user-responsive and hard working
  • 25. © 2016 SAP SE or an SAP affiliate company. All rights reserved. 25 Hit PAUSE, and discuss Questions?