SlideShare a Scribd company logo
1 of 42
Serversideness




Douglas Crockford
   Yahoo! Inc.
Server Side JavaScript
•
    1996 Netscape LiveWire
    PHP-like.
    Fail.

•
    Now Node.js on V8.
    Event driven, turn based execution.
    Win.
node.js
•
  node.js implements a web server in a
  JavaScript event loop.
•
  It is a high-performance event pump.
fs.readFile(filename, encoding,
    function (err, data) {...})
•
  Everything is (or can be) non-
  blocking.
•
  Except:
    –
        some synchronous functions
    –
        require
Your stuff runs on both sides

  Your stuff        Your stuff

    YUI3              YUI3

 DOM   node.js    DOM
                             JS
    JS/V8        Browser
Turn
•
    A turn is started by an external
    event, such as the completion of an
    asynchronous request, a user action,
    or the ticking of the clock.
•
    A callback function associated with
    the event is called. It runs to
    completion. When it returns, the turn
    ends.
•
    No need for threads. No races. No
    deadlocks.
The Law of Turns


 Never wait.
 Never block.
  Finish fast.
Turns
•
    Nothing can ever block, not even I/O.
•
    Do not poll. Instead, register a
    callback.
•
    This is how browsers work.
•
    This is how servers should also work.
Long running tasks
•
    Two solutions for long running
    programs:

•
    Eteration: Break the task into
    multiple turns.

•
    Move the task into a separate
    process (workers).
Threads are evil
•
    In systems programming, threads are
    a necessary evil.
•
    In application programming, threads
    are just evil.
•
    Threads provide a deceptively simple
    model of concurrency.
•
    Threads are subject to races and
    deadlocks.
Two threads
•
     my_array = [];
1.   my_array[my_array.length] = 'a';
2.   my_array[my_array.length] = 'b';

•.
     ['a', 'b']
•.
     ['b', 'a']
Two threads
•
     my_array = [];
1.   my_array[my_array.length] = 'a';
2.   my_array[my_array.length] = 'b';

•.
     ['a', 'b']
•.
     ['b', 'a']
•.
     ['a']
•.
     ['b']
my_array[my_array.length] = 'a';


length_a = my_array.length;
my_array[length_a] = 'a';
if (length_a >= my_array.length) {
    my_array.length = length_a + 1;
}
my_array[my_array.length] = 'a';
my_array[my_array.length] = 'b';

length_a = my_array.length;
length_b = my_array.length;
my_array[length_a] = 'a';
if (length_a >= my_array.length)
{
my_array[length_b] = 'b';
    my_array.length = length_a +
1;
}
It is impossible to have
application integrity when
subject to race conditions.
  Read - Modify - Write
Mutual Exclusion
•
    semaphore
•
    monitor
•
    rendezvous
•
    synchronization

•
    This used to be operating system
    stuff.
•
    It has leaked into applications
    because of networking and the multi-
Deadlock
Deadlock
Remote Procedure Call
•
    Combines two great ideas, functions
    and networking, producing a really
    bad idea.
•
    Attempts to isolate programs from
    time. The program blacks out.
•
    In reading the program, it is by
    design difficult to see where time is
    lost.
•
    This can result in a terrible
    experience for the user. Lost time
Turn-based program
avoids the problems
but is unfamiliar to
  non-JavaScript
  programmers.
Quiz 1

function funky(o) {
    o = null;
}

var x = [];
funky(x);              A.   null
                       B.   []
                       C.   undefined
alert(x);
                       D.   throw
Quiz 2

function swap(a, b) {
    var temp = a;
    a = b;
    b = temp
}
var x = 1, y = 2;       A.   1
swap(x, y);             B.   2
                        C.   undefined
                        D.   throw
alert(x);
Quiz 3

Make a function that puts a value in a
    variable when it is finished.
Pass the name of the
             variable.
function do_it(inputs, name) {
    ...
    eval(name + ' = ' + result);
    window[name] = result;
}

•
    Not only bad practice, but illegal in
    ES5/strict.
function do_it(inputs, obj, name) {
    ...
    obj[name] = result;
}

•
    Gives do-it too much authority.
function do_it(inputs, func) {
    ...
    func(result);
}

•
    We pass a function to do_it.
•
    do_it cannot abuse the function.
•
    The function cannot abuse do_it.
•
    func is a callback.
Callbacks
•
    Temporal isolation.
•
    Event handlers.
•
    Timers.
•
    Lightweight, powerful, expressive.

•
    Continuation.
function do_it(inputs, callback) {
    ...
    callback(result);
}



do_it(my_inputs, function (result) {
    my_object.blah = result;
});
Generalize.

function storer(obj, name) {
    return function (result) {
        obj[name] = result;
    };
}

do_it(inputs,
    storer(my_object, 'blah'));
function storer_maker(obj) {
   return function(name) {
       return function (result) {
            obj[name] = result;
       };
    };
}

my_storer = storer_maker(my_object);
do_it(my_inputs, my_storer('blah'));
function once(func) {
    return function () {
        var f = func;
        func = null;
        return f.apply(this,
arguments);
    };
}

do_it(my_inputs,
function sequence() {
    var slice = Array.prototype.slice,
         functions =
             slice.call(arguments, 0);
    return function () {
         var args = slice.call(arguments,
0);
         functions.forEach(function
(func) {
             func.apply(null, args);
function revokerness(func) {
    return {
        revocable: function () {
            return func.apply(this,
                    arguments);
        },
        revoker: function () {
            func = null;
        }
    };
do_it(my_inputs, once(sequence(
     storer(my_object, 'blah'),
     storer(other_object, 'wow'),
     alert
)));
Server programming can be
        more complicated.
•
    Call 20 services, each contributing
    material for the page, wait until all
    respond, then assemble the result.

•
    Call a service, use its result to call
    another service, avoiding deeply
    nested event handlers.
Requestor

function requestor(sync) {
    service_request(param,
        function (error, result) {
            sync(error, result);
        });
}
Requestor maker

function request_maker(param) {
   return function (sync) {
       service_request(param,
           function (error, result) {
               sync(error, result);
           });
   };
}
Requestor maker maker

function request_maker_maker(service) {
    return function (param) {
        return function (sync) {
           service(param,
               function (error, result) {
                   sync(error, result);
               });
        };
   };
}
Requestor maker maker

request_maker_maker
    (service)
    (param)
    (sync);
Composition

par([requestor…], sync, timeout);

seq([requestor…], sync, timeout);

map([requestor…], sync, timeout);
Composition function
         makers
paror([requestor…], timeout)

seqor([requestor…], timeout)

mapor([requestor…], timeout)
Also see
•
 Directing JavaScript with Arrows
www.cs.umd.edu/~mwh/papers/jsarro
ws.pdf

•
  Reactive Extensions for JavaScript
http://blogs.msdn.com/b/rxteam/archiv
e/
2010/03/17/reactive-extensions-for-
javascript.aspx
Thank you and good night.

More Related Content

What's hot

LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
Nick Sieger
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
Alexander Mostovenko
 

What's hot (20)

Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
Map kit light
Map kit lightMap kit light
Map kit light
 
Realm.io par Clement Sauvage
Realm.io par Clement SauvageRealm.io par Clement Sauvage
Realm.io par Clement Sauvage
 
Avoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.jsAvoiding Callback Hell with Async.js
Avoiding Callback Hell with Async.js
 
EcmaScript 6 - The future is here
EcmaScript 6 - The future is hereEcmaScript 6 - The future is here
EcmaScript 6 - The future is here
 
Asynchronous programming done right - Node.js
Asynchronous programming done right - Node.jsAsynchronous programming done right - Node.js
Asynchronous programming done right - Node.js
 
Functional programming principles
Functional programming principlesFunctional programming principles
Functional programming principles
 
Understanding Asynchronous JavaScript
Understanding Asynchronous JavaScriptUnderstanding Asynchronous JavaScript
Understanding Asynchronous JavaScript
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Callbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascriptCallbacks, promises, generators - asynchronous javascript
Callbacks, promises, generators - asynchronous javascript
 
Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6Introduction to Ecmascript - ES6
Introduction to Ecmascript - ES6
 
What's New in ES6 for Web Devs
What's New in ES6 for Web DevsWhat's New in ES6 for Web Devs
What's New in ES6 for Web Devs
 
ES6 PPT FOR 2016
ES6 PPT FOR 2016ES6 PPT FOR 2016
ES6 PPT FOR 2016
 
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
JRuby + Rails = Awesome Java Web Framework at Jfokus 2011
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
bluespec talk
bluespec talkbluespec talk
bluespec talk
 
No JS and DartCon
No JS and DartConNo JS and DartCon
No JS and DartCon
 

Similar to Douglas Crockford: Serversideness

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Node js
Node jsNode js
Node js
hazzaz
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
Ran Mizrahi
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
Tom Croucher
 

Similar to Douglas Crockford: Serversideness (20)

JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Awesomeness of JavaScript…almost
Awesomeness of JavaScript…almostAwesomeness of JavaScript…almost
Awesomeness of JavaScript…almost
 
3 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 20153 things you must know to think reactive - Geecon Kraków 2015
3 things you must know to think reactive - Geecon Kraków 2015
 
TypeScript for Java Developers
TypeScript for Java DevelopersTypeScript for Java Developers
TypeScript for Java Developers
 
Emerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the HorizonEmerging Languages: A Tour of the Horizon
Emerging Languages: A Tour of the Horizon
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
Queue your work
Queue your workQueue your work
Queue your work
 
Javascript Everywhere
Javascript EverywhereJavascript Everywhere
Javascript Everywhere
 
Sane Async Patterns
Sane Async PatternsSane Async Patterns
Sane Async Patterns
 
Node js
Node jsNode js
Node js
 
Intro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran MizrahiIntro To JavaScript Unit Testing - Ran Mizrahi
Intro To JavaScript Unit Testing - Ran Mizrahi
 
JS Essence
JS EssenceJS Essence
JS Essence
 
Advanced JavaScript
Advanced JavaScript Advanced JavaScript
Advanced JavaScript
 
Re-Design with Elixir/OTP
Re-Design with Elixir/OTPRe-Design with Elixir/OTP
Re-Design with Elixir/OTP
 
Playing With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.jsPlaying With Fire - An Introduction to Node.js
Playing With Fire - An Introduction to Node.js
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
 
Event driven javascript
Event driven javascriptEvent driven javascript
Event driven javascript
 
Intro to React
Intro to ReactIntro to React
Intro to React
 
Performance patterns
Performance patternsPerformance patterns
Performance patterns
 
Writing robust Node.js applications
Writing robust Node.js applicationsWriting robust Node.js applications
Writing robust Node.js applications
 

More from WebExpo

Michal Blažej: Zbavte sa account managementu
Michal Blažej: Zbavte sa account managementuMichal Blažej: Zbavte sa account managementu
Michal Blažej: Zbavte sa account managementu
WebExpo
 
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačkaJan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
WebExpo
 

More from WebExpo (20)

Jakub Vrána: Code Reviews with Phabricator
Jakub Vrána: Code Reviews with PhabricatorJakub Vrána: Code Reviews with Phabricator
Jakub Vrána: Code Reviews with Phabricator
 
Jaroslav Šnajdr: Getting a Business Collaboration Service Into Cloud: A Case ...
Jaroslav Šnajdr: Getting a Business Collaboration Service Into Cloud: A Case ...Jaroslav Šnajdr: Getting a Business Collaboration Service Into Cloud: A Case ...
Jaroslav Šnajdr: Getting a Business Collaboration Service Into Cloud: A Case ...
 
Steve Corona: Scaling LAMP doesn't have to suck
Steve Corona: Scaling LAMP doesn't have to suckSteve Corona: Scaling LAMP doesn't have to suck
Steve Corona: Scaling LAMP doesn't have to suck
 
Adii Pienaar: Lessons learnt running a global startup from the edge of the world
Adii Pienaar: Lessons learnt running a global startup from the edge of the worldAdii Pienaar: Lessons learnt running a global startup from the edge of the world
Adii Pienaar: Lessons learnt running a global startup from the edge of the world
 
Patrick Zandl: Energy industry post Edison, Křižík & IoT
Patrick Zandl: Energy industry post Edison, Křižík & IoTPatrick Zandl: Energy industry post Edison, Křižík & IoT
Patrick Zandl: Energy industry post Edison, Křižík & IoT
 
Ameya Kanitkar: Using Hadoop and HBase to Personalize Web, Mobile and Email E...
Ameya Kanitkar: Using Hadoop and HBase to Personalize Web, Mobile and Email E...Ameya Kanitkar: Using Hadoop and HBase to Personalize Web, Mobile and Email E...
Ameya Kanitkar: Using Hadoop and HBase to Personalize Web, Mobile and Email E...
 
Marli Mesibov - What's in a Story?
Marli Mesibov - What's in a Story?Marli Mesibov - What's in a Story?
Marli Mesibov - What's in a Story?
 
Tomáš Procházka: Moje zápisky z designu
Tomáš Procházka: Moje zápisky z designuTomáš Procházka: Moje zápisky z designu
Tomáš Procházka: Moje zápisky z designu
 
Jiří Knesl: Souboj frameworků
Jiří Knesl: Souboj frameworkůJiří Knesl: Souboj frameworků
Jiří Knesl: Souboj frameworků
 
Richard Fridrich: Buď punkový konzument!
Richard Fridrich: Buď punkový konzument!Richard Fridrich: Buď punkový konzument!
Richard Fridrich: Buď punkový konzument!
 
Jakub Nešetřil: Jak (ne)dělat API
Jakub Nešetřil: Jak (ne)dělat APIJakub Nešetřil: Jak (ne)dělat API
Jakub Nešetřil: Jak (ne)dělat API
 
Michal Blažej: Zbavte sa account managementu
Michal Blažej: Zbavte sa account managementuMichal Blažej: Zbavte sa account managementu
Michal Blažej: Zbavte sa account managementu
 
Denisa Lorencová: UX Designer - Anděl s ďáblem v těle
Denisa Lorencová: UX Designer - Anděl s ďáblem v těleDenisa Lorencová: UX Designer - Anděl s ďáblem v těle
Denisa Lorencová: UX Designer - Anděl s ďáblem v těle
 
Petr Ludwig: Jak bojovat s prokrastinací?
Petr Ludwig: Jak bojovat s prokrastinací?Petr Ludwig: Jak bojovat s prokrastinací?
Petr Ludwig: Jak bojovat s prokrastinací?
 
Jan Vlček: Gamifikace 101
Jan Vlček: Gamifikace 101Jan Vlček: Gamifikace 101
Jan Vlček: Gamifikace 101
 
Luke Wroblewski: Mobile First
Luke Wroblewski: Mobile FirstLuke Wroblewski: Mobile First
Luke Wroblewski: Mobile First
 
Adam Hrubý: Evoluce designéra
Adam Hrubý: Evoluce designéraAdam Hrubý: Evoluce designéra
Adam Hrubý: Evoluce designéra
 
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačkaJan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
Jan Sotorník: Grafika e-shopu jako sexy a chytrá prodavačka
 
Jana Štěpánová: Neziskovky Goes Web
Jana Štěpánová: Neziskovky Goes WebJana Štěpánová: Neziskovky Goes Web
Jana Štěpánová: Neziskovky Goes Web
 
Richard Fridrich: 5 x *, * a */5
Richard Fridrich: 5 x *, * a */5Richard Fridrich: 5 x *, * a */5
Richard Fridrich: 5 x *, * a */5
 

Recently uploaded

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Recently uploaded (20)

What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

Douglas Crockford: Serversideness

  • 2. Server Side JavaScript • 1996 Netscape LiveWire PHP-like. Fail. • Now Node.js on V8. Event driven, turn based execution. Win.
  • 3. node.js • node.js implements a web server in a JavaScript event loop. • It is a high-performance event pump. fs.readFile(filename, encoding, function (err, data) {...}) • Everything is (or can be) non- blocking. • Except: – some synchronous functions – require
  • 4. Your stuff runs on both sides Your stuff Your stuff YUI3 YUI3 DOM node.js DOM JS JS/V8 Browser
  • 5. Turn • A turn is started by an external event, such as the completion of an asynchronous request, a user action, or the ticking of the clock. • A callback function associated with the event is called. It runs to completion. When it returns, the turn ends. • No need for threads. No races. No deadlocks.
  • 6. The Law of Turns Never wait. Never block. Finish fast.
  • 7. Turns • Nothing can ever block, not even I/O. • Do not poll. Instead, register a callback. • This is how browsers work. • This is how servers should also work.
  • 8. Long running tasks • Two solutions for long running programs: • Eteration: Break the task into multiple turns. • Move the task into a separate process (workers).
  • 9. Threads are evil • In systems programming, threads are a necessary evil. • In application programming, threads are just evil. • Threads provide a deceptively simple model of concurrency. • Threads are subject to races and deadlocks.
  • 10. Two threads • my_array = []; 1. my_array[my_array.length] = 'a'; 2. my_array[my_array.length] = 'b'; •. ['a', 'b'] •. ['b', 'a']
  • 11. Two threads • my_array = []; 1. my_array[my_array.length] = 'a'; 2. my_array[my_array.length] = 'b'; •. ['a', 'b'] •. ['b', 'a'] •. ['a'] •. ['b']
  • 12. my_array[my_array.length] = 'a'; length_a = my_array.length; my_array[length_a] = 'a'; if (length_a >= my_array.length) { my_array.length = length_a + 1; }
  • 13. my_array[my_array.length] = 'a'; my_array[my_array.length] = 'b'; length_a = my_array.length; length_b = my_array.length; my_array[length_a] = 'a'; if (length_a >= my_array.length) { my_array[length_b] = 'b'; my_array.length = length_a + 1; }
  • 14. It is impossible to have application integrity when subject to race conditions. Read - Modify - Write
  • 15. Mutual Exclusion • semaphore • monitor • rendezvous • synchronization • This used to be operating system stuff. • It has leaked into applications because of networking and the multi-
  • 18. Remote Procedure Call • Combines two great ideas, functions and networking, producing a really bad idea. • Attempts to isolate programs from time. The program blacks out. • In reading the program, it is by design difficult to see where time is lost. • This can result in a terrible experience for the user. Lost time
  • 19. Turn-based program avoids the problems but is unfamiliar to non-JavaScript programmers.
  • 20. Quiz 1 function funky(o) { o = null; } var x = []; funky(x); A. null B. [] C. undefined alert(x); D. throw
  • 21. Quiz 2 function swap(a, b) { var temp = a; a = b; b = temp } var x = 1, y = 2; A. 1 swap(x, y); B. 2 C. undefined D. throw alert(x);
  • 22. Quiz 3 Make a function that puts a value in a variable when it is finished.
  • 23. Pass the name of the variable. function do_it(inputs, name) { ... eval(name + ' = ' + result); window[name] = result; } • Not only bad practice, but illegal in ES5/strict.
  • 24. function do_it(inputs, obj, name) { ... obj[name] = result; } • Gives do-it too much authority.
  • 25. function do_it(inputs, func) { ... func(result); } • We pass a function to do_it. • do_it cannot abuse the function. • The function cannot abuse do_it. • func is a callback.
  • 26. Callbacks • Temporal isolation. • Event handlers. • Timers. • Lightweight, powerful, expressive. • Continuation.
  • 27. function do_it(inputs, callback) { ... callback(result); } do_it(my_inputs, function (result) { my_object.blah = result; });
  • 28. Generalize. function storer(obj, name) { return function (result) { obj[name] = result; }; } do_it(inputs, storer(my_object, 'blah'));
  • 29. function storer_maker(obj) { return function(name) { return function (result) { obj[name] = result; }; }; } my_storer = storer_maker(my_object); do_it(my_inputs, my_storer('blah'));
  • 30. function once(func) { return function () { var f = func; func = null; return f.apply(this, arguments); }; } do_it(my_inputs,
  • 31. function sequence() { var slice = Array.prototype.slice, functions = slice.call(arguments, 0); return function () { var args = slice.call(arguments, 0); functions.forEach(function (func) { func.apply(null, args);
  • 32. function revokerness(func) { return { revocable: function () { return func.apply(this, arguments); }, revoker: function () { func = null; } };
  • 33. do_it(my_inputs, once(sequence( storer(my_object, 'blah'), storer(other_object, 'wow'), alert )));
  • 34. Server programming can be more complicated. • Call 20 services, each contributing material for the page, wait until all respond, then assemble the result. • Call a service, use its result to call another service, avoiding deeply nested event handlers.
  • 35. Requestor function requestor(sync) { service_request(param, function (error, result) { sync(error, result); }); }
  • 36. Requestor maker function request_maker(param) { return function (sync) { service_request(param, function (error, result) { sync(error, result); }); }; }
  • 37. Requestor maker maker function request_maker_maker(service) { return function (param) { return function (sync) { service(param, function (error, result) { sync(error, result); }); }; }; }
  • 38. Requestor maker maker request_maker_maker (service) (param) (sync);
  • 39. Composition par([requestor…], sync, timeout); seq([requestor…], sync, timeout); map([requestor…], sync, timeout);
  • 40. Composition function makers paror([requestor…], timeout) seqor([requestor…], timeout) mapor([requestor…], timeout)
  • 41. Also see • Directing JavaScript with Arrows www.cs.umd.edu/~mwh/papers/jsarro ws.pdf • Reactive Extensions for JavaScript http://blogs.msdn.com/b/rxteam/archiv e/ 2010/03/17/reactive-extensions-for- javascript.aspx
  • 42. Thank you and good night.