SlideShare a Scribd company logo
Max Klymyshyn
CartFresh
Fighting async JavaScript
CartFresh
GVMachinesInc.
‣ GroceryDeliverystartup
‣ WorkinginUkraineas ZAKAZ.UA(Kiev,
Dnepropetrovsk,Kharkiv)andas CartFresh(Boston,
US)
‣ React.jsonfront-end
‣ Python onback-end
theproblem
AsynchronousI/O
asynchronousI/OleadstocallbackAPI’s,
which leadtonestedlambdas,
which leadto…thepyramidof doom:
range.on("preheat", function() {
pot.on("boil", function() {
rice.on("cooked", function() {
dinner.serve(rice);
});
});
});
Pyramidof doom
clusterfuck.
Understandingthecode
‣ IBM1989: 50%of theeffortinaccomplishinga taskfortheprogrammeris
towardsunderstandingthesystem
‣ BellLabs1992:60%-80%of theirtime understandingcode,20% asthe
developersgainexperiencewith currentcodebase
‣ NationalResearchCouncil1997(Canada):over25% of theirtimeeither
searchingfor orlookingatcode
‣ Microsoft2006:50%
‣ PeterHallam2006:70%duringpersonal experiment
‣ Microsoft2007:65%(survey)
[1]
Fighting async JavaScript (CSP)
Promises
var greetingPromise = sayHello();
greetingPromise
.then(addExclamation)
.then(function (greeting) {
console.log(greeting); // hello world!!!!
}, function(error) {
// 'uh oh: something bad happened
console.error('uh oh: ', error);
});
function loadStory() {
return getJSON('story.json').then(function(story) {
addHtmlToPage(story.heading);
return story.chapterURLs.map(getJSON)
.reduce(function(chain, chapterPromise) {
return chain.then(function() {
return chapterPromise;
}).then(function(chapter) {
addHtmlToPage(chapter.html);
});
}, Promise.resolve());
}).then(function() {
addTextToPage("All done");
}).catch(function(err) {
addTextToPage("Argh, broken: " + err.message);
}).then(function() {
document.querySelector('.spinner').style.display =
'none';
});
}
Await
async function loadStory() {
try {
let story = await getJSON('story.json');
addHtmlToPage(story.heading);
for (let chapter of story.chapterURLs.map(getJSON)) {
addHtmlToPage((await chapter).html);
}
addTextToPage("All done");
} catch (err) {
addTextToPage("Argh, broken: " + err.message);
}
document.querySelector('.spinner').style.display = 'none';
}
(async function() {
await loadStory();
console.log("Yey, story successfully loaded!");
}());
[5] [6] [7]
FRP/RxJS
const $input = $('#input');
const $results = $('#results');
/* Only get the value from each key up */
var keyups = Rx.Observable.fromEvent($input, 'keyup')
.pluck('target', 'value')
.filter(text => text.length > 2 );
/* Now debounce the input for 500ms */
var debounced = keyups.debounce(500 /* ms */);
/* Now get only distinct values, so we eliminate the
arrows and other control characters */
var distinct = debounced.distinctUntilChanged();
[4]
Actormodel
(function () {
var spawn = WebActors.spawn;
var receive = WebActors.receive;
var send = WebActors.send, ANY = WebActors.ANY;
function aCallback() {
receive(ANY, function (message) {
alert(message);
});
}
actor = spawn(aCallback); // create an actor
send(actor, "a message"); // send it a message
})();
[2] [3]
CSP
Communicatingsequentialprocesses
CSP
‣ initially isaformallanguagefordescribingpatterns
of interactionin concurrentsystems
‣ firstdescribedina1978paperby TonyHoare
‣ influentialinthe designof the occam,Go,Limbo
‣ core.asyncin clojure
‣ js-cspforJS
Key points
‣ CSPcreatedforcommunicatingbetweendifferent
componentsandsubsystems
‣ CSPsolveproblemof coordinatinganythingasynchronous
‣ CSPalongsideotherssolveproblemof easy-to-
understandcode
example
import {chan, take, CLOSED, timeout, put} from "js-csp";
var ch = chan();
go(function*() {
var val;
while((val = yield take(ch)) !== CLOSED) {
console.log(val);
}
});
go(function*() {
yield put(ch, 1);
yield take(timeout(1000));
yield put(ch, 2);
ch.close();
});
[8]
Fighting async JavaScript (CSP)
real-world
export class Suggest extends React.Component {
constructor(props) {
super(props);
this.state = {active: -1, suggests: props.suggests}}
componentWillReceiveProps(nextProps) {
switch(nextProps.code) {
case 38:
this.setState({active: Math.max(-1, this.state.active - 1)});
break;
case 40:
this.setState({
active: Math.min(this.props.suggests.length - 1, this.state.active + 1)});
break;
case 13:
search(this.props.suggests[this.state.active]);
this.setState({suggests: []});
break;
default:
this.setState({suggests: nextProps.suggests});
}
}
render() {
return (<ul className="dropdown dropdown-menu">
{this.state.suggests.map((e, n) =>
<li key={e} className={...}><a href="#">{e}</a></li>)}
</ul>);
}}
function listen(el, type) {
var ch = chan();
el.addEventListener(type, e => {
putAsync(ch, [e.keyCode, el.value]);
e.preventDefault();
});
return ch;
}
export function suggest(elem) {
var el = elem[0];
go(function * () {
var keydown = listen(el, 'keydown');
while(true) {
var [code, value] = yield take(keydown);
var response = yield take(Storage.sync([
["store.suggest", {query: value}, {id: "suggest"}]]));
ReactDOM.render(
<Suggest suggests={response.suggests || []} code={code} value={value} />,
document.getElementById("suggest"));
}
});
}
Fighting async JavaScript (CSP)
Fighting async JavaScript (CSP)
synccode
Toolstowrite in syncstyle?
‣ Promises,Promiseswith generators
‣ Generators
‣ Async/wait
‣ Usingjs-csp(withgenerators)
synccode
withjs-csp
Tools
‣ Events
‣ XMLHttpRequest/HTTP
‣ WebSockets
‣ Timers
‣ Webworkers
Runtimeforlow-levelasync operations:getURL
import {buffers, go, chan, putAsync, operations} from "js-csp";
export function listen(el, type, options={}) {
/**
* Translate events into CSP channel untile channel is not closed.
*/
var {channel, prevent} = options;
var ch = channel || chan();
var listener = (e) => {
if (ch.closed === true) el.removeEventListener(type, listener);
else putAsync(ch, e);
if (prevent === true) e.preventDefault();
}
el.addEventListener(type, listener);
return ch;
}
import {go, take, timeout, CLOSED, close, chan, buffers} from "js-csp";
import {listen} from "./runtime.js";
var mousemove = listen(document, "mousemove", true, {channel: chan(buffers.
dropping(1))});
var target = document.getElementById("coords");
go(function * () {
var coords;
while((coords = yield take(mousemove)) !== CLOSED) {
target.innerHTML = `X=${coords.clientX} Y=${coords.clientY}`;
}
});
go(function * () {
yield timeout(3000);
yield mousemove.close();
target.innerHTML = 'interrupted.';
});
Fighting async JavaScript (CSP)
import {buffers, go, chan, putAsync, take,} from "js-csp";
export function json(options) {
var ch = chan();
go(function * () {
var value = yield take(request(options));
if(!(value instanceof Error)) {
value = JSON.parse(value);
} else {
console.error("Can't get " + options.url, value);
}
putAsync(ch, value);
});
return ch;
}
Features
‣ Channelbuffering:fixedsize,sliding,dropping
‣ pollvalues:takingimmediately
‣ alts:waitforvalueor executesecondoperation
Commonprocesses communication features
Extra features
‣ Reducechannelvalues
‣ splitvaluesof channels
‣ merge channels
‣ mult– supply valuesintotwochannels
‣ Pub/Submode
‣ Filteringwithpredicates and/ortransducers
thanks.
@maxmaxmaxmax
References
1.No,YouarenotDumb!Programmersdospendalotof timeUnderstandingCode…
http://blog.architexa.com/2010/05/no-you-are-not-dumb-programmers-do-spend-a-lot-of-time-understanding-code/
2.AnActormodelexamplewithAkka.NET
http://blog.geist.no/an-actor-model-example-with-akka-net/
3.WebActors
https://github.com/mental/webactors
4.TheReactiveExtensions forJavaScript (RxJS)
https://github.com/Reactive-Extensions/RxJS
5.ES7asyncfunctions-astepin the wrongdirection
https://spion.github.io/posts/es7-async-await-step-in-the-wrong-direction.html
6.Why coroutineswon’tworkon theweb
http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/
7.ImplementationStrategiesfor First-ClassContinuations*
http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=3668F1FC41AF1C1880B3062100057381?doi=10.1.1.70.9076&rep=rep1&type=pdf
8.Taming theAsynchronous Beast withCSPChannelsinJavaScript
http://jlongster.com/Taming-the-Asynchronous-Beast-with-CSP-in-JavaScript
Ad

Recommended

Communicating Sequential Processes (CSP) in JavaScript
Communicating Sequential Processes (CSP) in JavaScript
Max Klymyshyn
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
Alexey Fyodorov
 
Functional Reactive Programming with RxJS
Functional Reactive Programming with RxJS
stefanmayer13
 
ESCMAScript 6: Get Ready For The Future. Now
ESCMAScript 6: Get Ready For The Future. Now
Krzysztof Szafranek
 
ClojureScript loves React, DomCode May 26 2015
ClojureScript loves React, DomCode May 26 2015
Michiel Borkent
 
ClojureScript for the web
ClojureScript for the web
Michiel Borkent
 
Full Stack Clojure
Full Stack Clojure
Michiel Borkent
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
Michael Barker
 
Minion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejs
Marcelo Gornstein
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Coroutines in Kotlin
Coroutines in Kotlin
Dmytro Zaitsev
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
Simon Maple
 
R-4.0の解説
R-4.0の解説
弘毅 露崎
 
Decentralized Stream Processing over Web-enabled Devices
Decentralized Stream Processing over Web-enabled Devices
Masiar Babazadeh
 
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
PROIDEA
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014
Romain Francois
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofit
Ted Liang
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
Is your profiler speaking the same language as you? -- Docklands JUG
Is your profiler speaking the same language as you? -- Docklands JUG
Simon Maple
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Miguel Arroyo
 
rxJava 2 tips and tricks
rxJava 2 tips and tricks
Stepan Goncharov
 
Asynchronní programování
Asynchronní programování
PeckaDesign.cz
 
Go Concurrency Basics
Go Concurrency Basics
ElifTech
 
Reactive Programming - ReactFoo 2020 - Aziz Khambati
Reactive Programming - ReactFoo 2020 - Aziz Khambati
Aziz Khambati
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 

More Related Content

What's hot (20)

Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
Michael Barker
 
Minion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejs
Marcelo Gornstein
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
Coroutines in Kotlin
Coroutines in Kotlin
Dmytro Zaitsev
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
Simon Maple
 
R-4.0の解説
R-4.0の解説
弘毅 露崎
 
Decentralized Stream Processing over Web-enabled Devices
Decentralized Stream Processing over Web-enabled Devices
Masiar Babazadeh
 
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
PROIDEA
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
R/C++ talk at earl 2014
R/C++ talk at earl 2014
Romain Francois
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofit
Ted Liang
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
Is your profiler speaking the same language as you? -- Docklands JUG
Is your profiler speaking the same language as you? -- Docklands JUG
Simon Maple
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Miguel Arroyo
 
rxJava 2 tips and tricks
rxJava 2 tips and tricks
Stepan Goncharov
 
Asynchronní programování
Asynchronní programování
PeckaDesign.cz
 
Go Concurrency Basics
Go Concurrency Basics
ElifTech
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Anton Arhipov
 
Lock? We don't need no stinkin' locks!
Lock? We don't need no stinkin' locks!
Michael Barker
 
Minion pool - a worker pool for nodejs
Minion pool - a worker pool for nodejs
Marcelo Gornstein
 
Riga Dev Day 2016 - Having fun with Javassist
Riga Dev Day 2016 - Having fun with Javassist
Anton Arhipov
 
The Ring programming language version 1.5.3 book - Part 89 of 184
The Ring programming language version 1.5.3 book - Part 89 of 184
Mahmoud Samir Fayed
 
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin. UA Mobile 2017.
UA Mobile
 
DevoxxPL: JRebel Under The Covers
DevoxxPL: JRebel Under The Covers
Simon Maple
 
Decentralized Stream Processing over Web-enabled Devices
Decentralized Stream Processing over Web-enabled Devices
Masiar Babazadeh
 
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
PROIDEA
 
JavaOne 2015 - Having fun with Javassist
JavaOne 2015 - Having fun with Javassist
Anton Arhipov
 
Dagger & rxjava & retrofit
Dagger & rxjava & retrofit
Ted Liang
 
Reactive programming with RxJS - ByteConf 2018
Reactive programming with RxJS - ByteConf 2018
Tracy Lee
 
Is your profiler speaking the same language as you? -- Docklands JUG
Is your profiler speaking the same language as you? -- Docklands JUG
Simon Maple
 
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
Miguel Arroyo
 
Asynchronní programování
Asynchronní programování
PeckaDesign.cz
 
Go Concurrency Basics
Go Concurrency Basics
ElifTech
 

Similar to Fighting async JavaScript (CSP) (20)

Reactive Programming - ReactFoo 2020 - Aziz Khambati
Reactive Programming - ReactFoo 2020 - Aziz Khambati
Aziz Khambati
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
IRJET- Website on Restaurant Management System using VUEJS and NODEJS Backend
IRJET- Website on Restaurant Management System using VUEJS and NODEJS Backend
IRJET Journal
 
ES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
How Reactive do we need to be
How Reactive do we need to be
Jana Karceska
 
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
GeeksLab Odessa
 
Advanced redux
Advanced redux
Boris Dinkevich
 
Build tons of multi-device JavaScript applications - Part 1 : Boilerplate, de...
Build tons of multi-device JavaScript applications - Part 1 : Boilerplate, de...
Skilld
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
QORDER PRESENTATION
QORDER PRESENTATION
MohsinDevjani
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
Thinking in react
Thinking in react
aashimadudeja
 
FRP and Bacon.js
FRP and Bacon.js
Starbuildr
 
SMART TREAT JUNCTION
SMART TREAT JUNCTION
IRJET Journal
 
Sprout core and performance
Sprout core and performance
Yehuda Katz
 
Sexy React Stack
Sexy React Stack
KMS Technology
 
Progressive Web Apps. What, why and how
Progressive Web Apps. What, why and how
Riza Fahmi
 
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
Tech in Asia ID
 
Creation Of Social Group in Full Stack Progressive Apparel Purchasing Web App
Creation Of Social Group in Full Stack Progressive Apparel Purchasing Web App
IRJET Journal
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
garbles
 
Reactive Programming - ReactFoo 2020 - Aziz Khambati
Reactive Programming - ReactFoo 2020 - Aziz Khambati
Aziz Khambati
 
Introduction to Backbone.js & Marionette.js
Introduction to Backbone.js & Marionette.js
Return on Intelligence
 
IRJET- Website on Restaurant Management System using VUEJS and NODEJS Backend
IRJET- Website on Restaurant Management System using VUEJS and NODEJS Backend
IRJET Journal
 
ES6 patterns in the wild
ES6 patterns in the wild
Joe Morgan
 
How Reactive do we need to be
How Reactive do we need to be
Jana Karceska
 
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
FrontendLab: Programming UI with FRP and Bacon js - Вячеслав Ворончук
GeeksLab Odessa
 
Build tons of multi-device JavaScript applications - Part 1 : Boilerplate, de...
Build tons of multi-device JavaScript applications - Part 1 : Boilerplate, de...
Skilld
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
Adding a modern twist to legacy web applications
Adding a modern twist to legacy web applications
Jeff Durta
 
FRP and Bacon.js
FRP and Bacon.js
Starbuildr
 
SMART TREAT JUNCTION
SMART TREAT JUNCTION
IRJET Journal
 
Sprout core and performance
Sprout core and performance
Yehuda Katz
 
Progressive Web Apps. What, why and how
Progressive Web Apps. What, why and how
Riza Fahmi
 
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
"Progressive Web Apps" by Riza Fahmi (Hacktiv8)
Tech in Asia ID
 
Creation Of Social Group in Full Stack Progressive Apparel Purchasing Web App
Creation Of Social Group in Full Stack Progressive Apparel Purchasing Web App
IRJET Journal
 
Strategies for Mitigating Complexity in React Based Redux Applicaitons
Strategies for Mitigating Complexity in React Based Redux Applicaitons
garbles
 
Ad

More from Max Klymyshyn (20)

Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Papers We Love Kyiv, July 2018: A Conflict-Free Replicated JSON Datatype
Max Klymyshyn
 
KharkivJS 2017: Коллаборативные системы и CRDT
KharkivJS 2017: Коллаборативные системы и CRDT
Max Klymyshyn
 
OdessaJS 2017: Groupware Systems for fun and profit
OdessaJS 2017: Groupware Systems for fun and profit
Max Klymyshyn
 
PyCon Ukraine 2017: Operational Transformation
PyCon Ukraine 2017: Operational Transformation
Max Klymyshyn
 
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
PiterPy 2016: Parallelization, Aggregation and Validation of API in Python
Max Klymyshyn
 
React.js: Ускоряем UX/UI
React.js: Ускоряем UX/UI
Max Klymyshyn
 
KharkovPy #12: I/O in Python apps and smart logging (russian)
KharkovPy #12: I/O in Python apps and smart logging (russian)
Max Klymyshyn
 
5 мифов о производительности баз данных и Python
5 мифов о производительности баз данных и Python
Max Klymyshyn
 
Изоформные приложения на React.js
Изоформные приложения на React.js
Max Klymyshyn
 
Изоморфный JavaScript (iForum 2015)
Изоморфный JavaScript (iForum 2015)
Max Klymyshyn
 
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Трансдюсеры, CSP каналы, неизменяемые структуры данных в JavaScript
Max Klymyshyn
 
PiterPy 2015 - Трансдюсеры и Python
PiterPy 2015 - Трансдюсеры и Python
Max Klymyshyn
 
Robust web apps with React.js
Robust web apps with React.js
Max Klymyshyn
 
LvivJS 2014 - Win-win c React.js
LvivJS 2014 - Win-win c React.js
Max Klymyshyn
 
Инновации и JavaScript
Инновации и JavaScript
Max Klymyshyn
 
Odessapy2013 - Graph databases and Python
Odessapy2013 - Graph databases and Python
Max Klymyshyn
 
Angular.js - JS Camp UKraine 2013
Angular.js - JS Camp UKraine 2013
Max Klymyshyn
 
Зачем читать чужой код?
Зачем читать чужой код?
Max Klymyshyn
 
AgileBaseCamp 2013 - Start Up and Get Done
AgileBaseCamp 2013 - Start Up and Get Done
Max Klymyshyn
 
PyCon 2012 - Data Driven Design
PyCon 2012 - Data Driven Design
Max Klymyshyn
 
Ad

Recently uploaded (20)

Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
Modern Platform Engineering with Choreo - The AI-Native Internal Developer Pl...
WSO2
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Streamlining CI/CD with FME Flow: A Practical Guide
Streamlining CI/CD with FME Flow: A Practical Guide
Safe Software
 
Simplify Insurance Regulations with Compliance Management Software
Simplify Insurance Regulations with Compliance Management Software
Insurance Tech Services
 
Advance Doctor Appointment Booking App With Online Payment
Advance Doctor Appointment Booking App With Online Payment
AxisTechnolabs
 
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
CodeCleaner: Mitigating Data Contamination for LLM Benchmarking
arabelatso
 
Best Practice for LLM Serving in the Cloud
Best Practice for LLM Serving in the Cloud
Alluxio, Inc.
 
Zoho Creator Solution for EI by Elsner Technologies.docx
Zoho Creator Solution for EI by Elsner Technologies.docx
Elsner Technologies Pvt. Ltd.
 
University Campus Navigation for All - Peak of Data & AI
University Campus Navigation for All - Peak of Data & AI
Safe Software
 
Heat Treatment Process Automation in India
Heat Treatment Process Automation in India
Reckers Mechatronics
 
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
IDM Crack with Internet Download Manager 6.42 Build 41 [Latest 2025]
pcprocore
 
AI for PV: Development and Governance for a Regulated Industry
AI for PV: Development and Governance for a Regulated Industry
Biologit
 
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Test Case Design Techniques – Practical Examples & Best Practices in Software...
Muhammad Fahad Bashir
 
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
Enable Your Cloud Journey With Microsoft Trusted Partner | IFI Tech
IFI Techsolutions
 
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Folding Cheat Sheet # 9 - List Unfolding 𝑢𝑛𝑓𝑜𝑙𝑑 as the Computational Dual of ...
Philip Schwarz
 
From Data Preparation to Inference: How Alluxio Speeds Up AI
From Data Preparation to Inference: How Alluxio Speeds Up AI
Alluxio, Inc.
 
Decipher SEO Solutions for your startup needs.
Decipher SEO Solutions for your startup needs.
mathai2
 
How Automation in Claims Handling Streamlined Operations
How Automation in Claims Handling Streamlined Operations
Insurance Tech Services
 
Introduction to Agile Frameworks for Product Managers.pdf
Introduction to Agile Frameworks for Product Managers.pdf
Ali Vahed
 
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
MOVIE RECOMMENDATION SYSTEM, UDUMULA GOPI REDDY, Y24MC13085.pptx
Maharshi Mallela
 

Fighting async JavaScript (CSP)

  • 2. CartFresh GVMachinesInc. ‣ GroceryDeliverystartup ‣ WorkinginUkraineas ZAKAZ.UA(Kiev, Dnepropetrovsk,Kharkiv)andas CartFresh(Boston, US) ‣ React.jsonfront-end ‣ Python onback-end
  • 5. range.on("preheat", function() { pot.on("boil", function() { rice.on("cooked", function() { dinner.serve(rice); }); }); }); Pyramidof doom
  • 8. ‣ IBM1989: 50%of theeffortinaccomplishinga taskfortheprogrammeris towardsunderstandingthesystem ‣ BellLabs1992:60%-80%of theirtime understandingcode,20% asthe developersgainexperiencewith currentcodebase ‣ NationalResearchCouncil1997(Canada):over25% of theirtimeeither searchingfor orlookingatcode ‣ Microsoft2006:50% ‣ PeterHallam2006:70%duringpersonal experiment ‣ Microsoft2007:65%(survey) [1]
  • 10. Promises var greetingPromise = sayHello(); greetingPromise .then(addExclamation) .then(function (greeting) { console.log(greeting); // hello world!!!! }, function(error) { // 'uh oh: something bad happened console.error('uh oh: ', error); });
  • 11. function loadStory() { return getJSON('story.json').then(function(story) { addHtmlToPage(story.heading); return story.chapterURLs.map(getJSON) .reduce(function(chain, chapterPromise) { return chain.then(function() { return chapterPromise; }).then(function(chapter) { addHtmlToPage(chapter.html); }); }, Promise.resolve()); }).then(function() { addTextToPage("All done"); }).catch(function(err) { addTextToPage("Argh, broken: " + err.message); }).then(function() { document.querySelector('.spinner').style.display = 'none'; }); }
  • 12. Await async function loadStory() { try { let story = await getJSON('story.json'); addHtmlToPage(story.heading); for (let chapter of story.chapterURLs.map(getJSON)) { addHtmlToPage((await chapter).html); } addTextToPage("All done"); } catch (err) { addTextToPage("Argh, broken: " + err.message); } document.querySelector('.spinner').style.display = 'none'; } (async function() { await loadStory(); console.log("Yey, story successfully loaded!"); }()); [5] [6] [7]
  • 13. FRP/RxJS const $input = $('#input'); const $results = $('#results'); /* Only get the value from each key up */ var keyups = Rx.Observable.fromEvent($input, 'keyup') .pluck('target', 'value') .filter(text => text.length > 2 ); /* Now debounce the input for 500ms */ var debounced = keyups.debounce(500 /* ms */); /* Now get only distinct values, so we eliminate the arrows and other control characters */ var distinct = debounced.distinctUntilChanged(); [4]
  • 14. Actormodel (function () { var spawn = WebActors.spawn; var receive = WebActors.receive; var send = WebActors.send, ANY = WebActors.ANY; function aCallback() { receive(ANY, function (message) { alert(message); }); } actor = spawn(aCallback); // create an actor send(actor, "a message"); // send it a message })(); [2] [3]
  • 16. CSP ‣ initially isaformallanguagefordescribingpatterns of interactionin concurrentsystems ‣ firstdescribedina1978paperby TonyHoare ‣ influentialinthe designof the occam,Go,Limbo ‣ core.asyncin clojure ‣ js-cspforJS
  • 17. Key points ‣ CSPcreatedforcommunicatingbetweendifferent componentsandsubsystems ‣ CSPsolveproblemof coordinatinganythingasynchronous ‣ CSPalongsideotherssolveproblemof easy-to- understandcode
  • 19. import {chan, take, CLOSED, timeout, put} from "js-csp"; var ch = chan(); go(function*() { var val; while((val = yield take(ch)) !== CLOSED) { console.log(val); } }); go(function*() { yield put(ch, 1); yield take(timeout(1000)); yield put(ch, 2); ch.close(); }); [8]
  • 22. export class Suggest extends React.Component { constructor(props) { super(props); this.state = {active: -1, suggests: props.suggests}} componentWillReceiveProps(nextProps) { switch(nextProps.code) { case 38: this.setState({active: Math.max(-1, this.state.active - 1)}); break; case 40: this.setState({ active: Math.min(this.props.suggests.length - 1, this.state.active + 1)}); break; case 13: search(this.props.suggests[this.state.active]); this.setState({suggests: []}); break; default: this.setState({suggests: nextProps.suggests}); } } render() { return (<ul className="dropdown dropdown-menu"> {this.state.suggests.map((e, n) => <li key={e} className={...}><a href="#">{e}</a></li>)} </ul>); }}
  • 23. function listen(el, type) { var ch = chan(); el.addEventListener(type, e => { putAsync(ch, [e.keyCode, el.value]); e.preventDefault(); }); return ch; } export function suggest(elem) { var el = elem[0]; go(function * () { var keydown = listen(el, 'keydown'); while(true) { var [code, value] = yield take(keydown); var response = yield take(Storage.sync([ ["store.suggest", {query: value}, {id: "suggest"}]])); ReactDOM.render( <Suggest suggests={response.suggests || []} code={code} value={value} />, document.getElementById("suggest")); } }); }
  • 27. Toolstowrite in syncstyle? ‣ Promises,Promiseswith generators ‣ Generators ‣ Async/wait ‣ Usingjs-csp(withgenerators)
  • 29. Tools ‣ Events ‣ XMLHttpRequest/HTTP ‣ WebSockets ‣ Timers ‣ Webworkers Runtimeforlow-levelasync operations:getURL
  • 30. import {buffers, go, chan, putAsync, operations} from "js-csp"; export function listen(el, type, options={}) { /** * Translate events into CSP channel untile channel is not closed. */ var {channel, prevent} = options; var ch = channel || chan(); var listener = (e) => { if (ch.closed === true) el.removeEventListener(type, listener); else putAsync(ch, e); if (prevent === true) e.preventDefault(); } el.addEventListener(type, listener); return ch; }
  • 31. import {go, take, timeout, CLOSED, close, chan, buffers} from "js-csp"; import {listen} from "./runtime.js"; var mousemove = listen(document, "mousemove", true, {channel: chan(buffers. dropping(1))}); var target = document.getElementById("coords"); go(function * () { var coords; while((coords = yield take(mousemove)) !== CLOSED) { target.innerHTML = `X=${coords.clientX} Y=${coords.clientY}`; } }); go(function * () { yield timeout(3000); yield mousemove.close(); target.innerHTML = 'interrupted.'; });
  • 33. import {buffers, go, chan, putAsync, take,} from "js-csp"; export function json(options) { var ch = chan(); go(function * () { var value = yield take(request(options)); if(!(value instanceof Error)) { value = JSON.parse(value); } else { console.error("Can't get " + options.url, value); } putAsync(ch, value); }); return ch; }
  • 34. Features ‣ Channelbuffering:fixedsize,sliding,dropping ‣ pollvalues:takingimmediately ‣ alts:waitforvalueor executesecondoperation Commonprocesses communication features
  • 35. Extra features ‣ Reducechannelvalues ‣ splitvaluesof channels ‣ merge channels ‣ mult– supply valuesintotwochannels ‣ Pub/Submode ‣ Filteringwithpredicates and/ortransducers
  • 37. References 1.No,YouarenotDumb!Programmersdospendalotof timeUnderstandingCode… http://blog.architexa.com/2010/05/no-you-are-not-dumb-programmers-do-spend-a-lot-of-time-understanding-code/ 2.AnActormodelexamplewithAkka.NET http://blog.geist.no/an-actor-model-example-with-akka-net/ 3.WebActors https://github.com/mental/webactors 4.TheReactiveExtensions forJavaScript (RxJS) https://github.com/Reactive-Extensions/RxJS 5.ES7asyncfunctions-astepin the wrongdirection https://spion.github.io/posts/es7-async-await-step-in-the-wrong-direction.html 6.Why coroutineswon’tworkon theweb http://calculist.org/blog/2011/12/14/why-coroutines-wont-work-on-the-web/ 7.ImplementationStrategiesfor First-ClassContinuations* http://citeseerx.ist.psu.edu/viewdoc/download;jsessionid=3668F1FC41AF1C1880B3062100057381?doi=10.1.1.70.9076&rep=rep1&type=pdf 8.Taming theAsynchronous Beast withCSPChannelsinJavaScript http://jlongster.com/Taming-the-Asynchronous-Beast-with-CSP-in-JavaScript