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

Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxSasikiranMarri
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingShane Coughlan
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsDEEPRAJ PATHAK
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?Alexandre Beguel
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...Bert Jan Schrijver
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfmaor17
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfkalichargn70th171
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfRTS corp
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdfAndrey Devyatkin
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxAS Design & AST.
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdfSteve Caron
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogueitservices996
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jNeo4j
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slidesvaideheekore1
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapIshara Amarasekera
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxRTS corp
 

Recently uploaded (20)

Understanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptxUnderstanding Plagiarism: Causes, Consequences and Prevention.pptx
Understanding Plagiarism: Causes, Consequences and Prevention.pptx
 
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full RecordingOpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
OpenChain AI Study Group - Europe and Asia Recap - 2024-04-11 - Full Recording
 
Effort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software ProjectsEffort Estimation Techniques used in Software Projects
Effort Estimation Techniques used in Software Projects
 
SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?SAM Training Session - How to use EXCEL ?
SAM Training Session - How to use EXCEL ?
 
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
JavaLand 2024 - Going serverless with Quarkus GraalVM native images and AWS L...
 
Zer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdfZer0con 2024 final share short version.pdf
Zer0con 2024 final share short version.pdf
 
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdfPros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
Pros and Cons of Selenium In Automation Testing_ A Comprehensive Assessment.pdf
 
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdfEnhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
Enhancing Supply Chain Visibility with Cargo Cloud Solutions.pdf
 
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
2024-04-09 - From Complexity to Clarity - AWS Summit AMS.pdf
 
Mastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptxMastering Project Planning with Microsoft Project 2016.pptx
Mastering Project Planning with Microsoft Project 2016.pptx
 
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
[ CNCF Q1 2024 ] Intro to Continuous Profiling and Grafana Pyroscope.pdf
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 
Ronisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited CatalogueRonisha Informatics Private Limited Catalogue
Ronisha Informatics Private Limited Catalogue
 
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4jGraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
GraphSummit Madrid - Product Vision and Roadmap - Luis Salvador Neo4j
 
Introduction to Firebase Workshop Slides
Introduction to Firebase Workshop SlidesIntroduction to Firebase Workshop Slides
Introduction to Firebase Workshop Slides
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
Key Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery RoadmapKey Steps in Agile Software Delivery Roadmap
Key Steps in Agile Software Delivery Roadmap
 
Advantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptxAdvantages of Cargo Cloud Solutions.pptx
Advantages of Cargo Cloud Solutions.pptx
 

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?