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

More Related Content

PDF
Communicating Sequential Processes (CSP) in JavaScript
PDF
Counter Wars (JEEConf 2016)
PPTX
Functional Reactive Programming with RxJS
PDF
ESCMAScript 6: Get Ready For The Future. Now
PDF
ClojureScript loves React, DomCode May 26 2015
PDF
ClojureScript for the web
PDF
Full Stack Clojure
PDF
JEEConf 2017 - Having fun with Javassist
Communicating Sequential Processes (CSP) in JavaScript
Counter Wars (JEEConf 2016)
Functional Reactive Programming with RxJS
ESCMAScript 6: Get Ready For The Future. Now
ClojureScript loves React, DomCode May 26 2015
ClojureScript for the web
Full Stack Clojure
JEEConf 2017 - Having fun with Javassist

What's hot (20)

PDF
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
KEY
Lock? We don't need no stinkin' locks!
PDF
Minion pool - a worker pool for nodejs
PDF
Riga Dev Day 2016 - Having fun with Javassist
PDF
The Ring programming language version 1.5.3 book - Part 89 of 184
PDF
Coroutines in Kotlin. UA Mobile 2017.
PDF
Coroutines in Kotlin
PDF
DevoxxPL: JRebel Under The Covers
PDF
R-4.0の解説
PDF
Decentralized Stream Processing over Web-enabled Devices
PDF
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
PDF
JavaOne 2015 - Having fun with Javassist
PDF
R/C++ talk at earl 2014
PDF
Dagger & rxjava & retrofit
PDF
Reactive programming with RxJS - ByteConf 2018
PDF
Is your profiler speaking the same language as you? -- Docklands JUG
PDF
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
PDF
rxJava 2 tips and tricks
PDF
Asynchronní programování
PPTX
Go Concurrency Basics
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Lock? We don't need no stinkin' locks!
Minion pool - a worker pool for nodejs
Riga Dev Day 2016 - Having fun with Javassist
The Ring programming language version 1.5.3 book - Part 89 of 184
Coroutines in Kotlin. UA Mobile 2017.
Coroutines in Kotlin
DevoxxPL: JRebel Under The Covers
R-4.0の解説
Decentralized Stream Processing over Web-enabled Devices
JDD2015: Frege - Introducing purely functional programming on the JVM - Dierk...
JavaOne 2015 - Having fun with Javassist
R/C++ talk at earl 2014
Dagger & rxjava & retrofit
Reactive programming with RxJS - ByteConf 2018
Is your profiler speaking the same language as you? -- Docklands JUG
Go Go Gadget! - An Intro to Return Oriented Programming (ROP)
rxJava 2 tips and tricks
Asynchronní programování
Go Concurrency Basics
Ad

Similar to Fighting async JavaScript (CSP) (20)

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

More from Max Klymyshyn (20)

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

Recently uploaded (20)

PPTX
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
PPTX
Airline CRS | Airline CRS Systems | CRS System
PPTX
Matchmaking for JVMs: How to Pick the Perfect GC Partner
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
PPTX
Lecture 5 Software Requirement Engineering
PDF
PDF-XChange Editor Plus 10.7.0.398.0 Crack Free Download Latest 2025
PPTX
Python is a high-level, interpreted programming language
PDF
CCleaner 6.39.11548 Crack 2025 License Key
PPTX
Full-Stack Developer Courses That Actually Land You Jobs
PDF
MCP Security Tutorial - Beginner to Advanced
PPTX
Download Adobe Photoshop Crack 2025 Free
PDF
AI-Powered Fuzz Testing: The Future of QA
PPTX
GSA Content Generator Crack (2025 Latest)
PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PDF
AI Guide for Business Growth - Arna Softech
PDF
Guide to Food Delivery App Development.pdf
PDF
Microsoft Office 365 Crack Download Free
PDF
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
DOCX
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx
Plex Media Server 1.28.2.6151 With Crac5 2022 Free .
Airline CRS | Airline CRS Systems | CRS System
Matchmaking for JVMs: How to Pick the Perfect GC Partner
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
Lecture 5 Software Requirement Engineering
PDF-XChange Editor Plus 10.7.0.398.0 Crack Free Download Latest 2025
Python is a high-level, interpreted programming language
CCleaner 6.39.11548 Crack 2025 License Key
Full-Stack Developer Courses That Actually Land You Jobs
MCP Security Tutorial - Beginner to Advanced
Download Adobe Photoshop Crack 2025 Free
AI-Powered Fuzz Testing: The Future of QA
GSA Content Generator Crack (2025 Latest)
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
AI Guide for Business Growth - Arna Softech
Guide to Food Delivery App Development.pdf
Microsoft Office 365 Crack Download Free
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
Modern SharePoint Intranet Templates That Boost Employee Engagement in 2025.docx

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