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

Build Lightweight Web Module
Build Lightweight Web ModuleBuild Lightweight Web Module
Build Lightweight Web Module
Morgan Cheng
 
Testing your javascript code with jasmine
Testing your javascript code with jasmineTesting your javascript code with jasmine
Testing your javascript code with jasmine
Rubyc Slides
 

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

The Workforce 2020
The Workforce 2020The Workforce 2020
The Workforce 2020
Argyle Executive Forum
 

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

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
 
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
 

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

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
masabamasaba
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
masabamasaba
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
chiefasafspells
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
masabamasaba
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
Health
 

Recently uploaded (20)

%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
%+27788225528 love spells in Huntington Beach Psychic Readings, Attraction sp...
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
%+27788225528 love spells in Colorado Springs Psychic Readings, Attraction sp...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Toronto Psychic Readings, Attraction spells,Brin...
 
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
%in Rustenburg+277-882-255-28 abortion pills for sale in Rustenburg
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
WSO2CON 2024 - Navigating API Complexity: REST, GraphQL, gRPC, Websocket, Web...
 
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
WSO2CON 2024 - API Management Usage at La Poste and Its Impact on Business an...
 
WSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security ProgramWSO2CON 2024 - How to Run a Security Program
WSO2CON 2024 - How to Run a Security Program
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 

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?