SlideShare a Scribd company logo
1 of 59
Download to read offline
Jscex
- 2011.10
•       /       / Jeffrey Zhao /

•
•         http://blog.zhaojie.me/

•         @

• F#, JavaScript, Scala, C#, Python, .NET, Mono...
• Java
Jscex

• JavaScript Computation EXpression
• JavaScript
• F#                      JavaScript
 •     “            ”
 •     JavaScript       JavaScript
Jscex

•
    •   Jscex              JavaScript

•
    •   Jscex                           /

• JavaScript           /
    •           ECMAScript 3
var compare = function (x, y) {
    return x - y;
}

var swap = function (a, i, j) {
    var t = a[i]; a[i] = a[j]; a[j] = t;
}

var bubbleSort = function (array) {
    for (var x = 0; x < array.length; x++) {
        for (var y = 0; y < array.length - x; y++) {
            if (compare(array[y], array[y + 1]) > 0) {
                swap(array, y, y + 1);
            }
        }
    }
}
var compare = function (x, y, callback) {         var innerLoop = function (array, x, y, callback) {
    setTimeout(10, function () {                      if (y < array.length - x) {
        callback(x - y);                                  compare(array[y], array[y + 1], function (r) {
    });                                                        if (r > 0) {
}                                                                  swap(array, y, y + 1, function () {
                                                                        innerLoop(array, x, y + 1, callback);
var swap = function (a, i, j, callback) {                          });
    var t = a[i]; a[i] = a[j]; a[j] = t;                       } else {
    repaint(a);                                                    innerLoop(array, x, y + 1, callback);
                                                               }
    setTimeout(20, callback);                             });
}                                                     } else {
                                                          callback();
var outerLoop = function (array, x, callback) {       }
    if (x < array) {                              }
        innerLoop(array, x, 0, function () {
             outerLoop(array, x + 1, callback);   outerLoop(array, 0, function () {
        });                                           console.log("done!");
    } else {                                      });
        callback();
    }
}
var compare = function (x, y, callback) {         var innerLoop = function (array, x, y, callback) {
    setTimeout(10, function () {                      if (y < array.length - x) {
        callback(x - y);                                  compare(array[y], array[y + 1], function (r) {
    });                                                        if (r > 0) {
}                                                                  swap(array, y, y + 1, function () {
                                                                        innerLoop(array, x, y + 1, callback);
var swap = function (a, i, j, callback) {                          });
    var t = a[i]; a[i] = a[j]; a[j] = t;                       } else {




                            D
    repaint(a);                                                    innerLoop(array, x, y + 1, callback);
                                                               }




                           M
    setTimeout(20, callback);                             });
}                                                     } else {



                         T
                                                          callback();
var outerLoop = function (array, x, callback) {       }
    if (x < array) {                              }
        innerLoop(array, x, 0, function () {
             outerLoop(array, x + 1, callback);   outerLoop(array, 0, function () {
        });                                           console.log("done!");
    } else {                                      });
        callback();
    }
}
var compareAsync = eval(Jscex.compile("async", function (x, y) {
     $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms.
     return x - y;
}));

var swapAsync = eval(Jscex.compile("async", function (a, i, j) {
     var t = a[i]; a[i] = a[j]; a[j] = t; // swap
     repaint(a); // repaint after each swap
     $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms.
}));

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0) $await(swapAsync(array, y, y + 1));
         }
     }
}));

                                http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
var compareAsync = eval(Jscex.compile("async", function (x, y) {
     $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms.
     return x - y;
}));

var swapAsync = eval(Jscex.compile("async", function (a, i, j) {
     var t = a[i]; a[i] = a[j]; a[j] = t; // swap
     repaint(a); // repaint after each swap
     $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms.
}));

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0) $await(swapAsync(array, y, y + 1));
         }
     }
}));
•
    •
    •
•
    •
    •
Jscex

//
var somethingAsync = eval(Jscex.compile("async",
    function (...) {
        //
    }
));
function () {
    var res = $await(<async work>);
}
function () {
    var res = $await(<async work>);
}

        HTTP
         UI


      Web Service
var f = eval(Jscex.compile("async", function () {
     var img = $await(readAsync("http://..."));
     console.log("loaded!");
     $await(writeAsync("./files/..."));
     console.log("saved!");
}));
…
var f = eval('(function () {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            _b_.Bind(readAsync(...), function (img) {
                console.log("loaded!");
                return _b_.Bind(writeAsync(...), function () {
                    console.log("saved!");
                    return _b_.Normal();
                });
            });
        })
    );
})');
…
var f = (function () {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            _b_.Bind(readAsync(...), function (img) {
                console.log("loaded!");
                return _b_.Bind(writeAsync(...), function () {
                    console.log("saved!");
                    return _b_.Normal();
                });
            });
        })
    );
});
Express
var app = express.createServer();

app.get('/', function (req, res) {
    /**
     *
     *
     * 1.
     * 2.
     *
     * 3.              res
     *
     *           “   ”
     **/
});

app.listen(3000);
Jscex
app.getAsync('/', eval(Jscex.compile("async", function (req, res) {

    var keys = $await(db.getKeysAsync(...));

    var results = [];
    for (var i = 0; i < keys.length; i++) {
        var r = $await(cache.getAsync(keys[i]));
        if (!r) {
            r = $await(db.getItemAsync(keys[i]));
        }

        results.push(r);
    }

    res.send(generateList(results));
})));
I/O

•             I/O
    •   Web
    •
•
• I/O
    •
var getItemAsync = eval(Jscex.compile("async", function (key) {
     var res = $await(cache.getAsync(key));
     if (res) return res;
     return $await(db.getItemAsync(key));
}));

app.getAsync('/', eval(Jscex.compile("async", function (req, res) {

    var keys = $await(db.getKeysAsync(...));

    //    “       ”
    var tasks = keys.map(function (key) {
        return getItemAsync(key);
    });

    //
    var results = $await(Jscex.Async.parallel(tasks));

    res.send(generateList(results));
})));
•
    •
    •      $await(Jscex.Async.parallel(taskA, taskB))

    •      $await(taskA.continueWith(taskB))


• $await
    •
    •
•
    •      taskA.start(); $await(taskB); $await(taskA);
//
var i = 1;
conn.onAsync("data", eval(Jscex.compile("async", function () {
	   var id = i++;

    $await(step1); console.log("step 1 - request " + id);
    $await(step2); console.log("step 2 - request " + id);

    /**
      *
      *     step   1   -   request   1
      *     step   1   -   request   2
      *     step   2   -   request   2
      *     step   2   -   request   1
      **/
})));
... the principle we go by is, don't expect to see
a particular concurrency model put into C#
because there're many different concurrency
model ... it's more about finding things are
common to all kinds of concurrency ...

                              - Anders Hejlsberg
Erlang
var i = 0;
var agent = Agent.start(eval(Jscex.compile("async", function (mailbox) {
    while (true) {
        var id = i++;

        var msg = $await(mailbox.receive());
        $await(step1); console.log("step 1 - request " + id);
        $await(step2); console.log("step 2 - request " + id);
    }
})));

conn.on("data", function (data) {
    //           mailbox
    agent.send(data);
});
Jscex

•       JavaScript
    •
    •
    •
•              “     ”
•                          JavaScript
    •            while / for / for...in / do
    •            if / switch
    •                 try...catch...finally
    •            return / break / continue / throw

•
    •   with
    •              break continue
    •   switch                 break

•
//
var somethingAsync = eval(Jscex.compile("async",
    function (...) {
        //
    }
));
eval
Sample = {
    //
    compile: function (func) {
        return "(" + func.toString() + ")";
    },

    //    eval
    compileEx: function (func) {
        return eval("(" + func.toString() + ")");
    }
}
eval
(function () {
    var a = 1;

    // f1
    var f1 = eval(Sample.compile(function () {
         alert(a);
    }));
    f1(); //     “1”

    // f2         Sample.compileEx
    var f2 = Sample.compileEx(function () {
        alert(a);
    });
    f2(); //    “a      ”
})();
•                 JavaScript

•       “bind”                 $await
    •
    •         “          ”
    •     “        ”
•       JavaScript

•
•
    •                     JIT
    •        JavaScript
“               ”
MyClass.prototype = {
    get: function (n) {
        ...
    },

    calculateAsync: eval(Jscex.compile("async", function (n) {
        var numbers = [];
        for (var i = 0; i < n; i++)
        	 numbers.push(i);
        	
        this.result = $await(make(numbers));
    }))
}
“                 ”
MyClass.prototype = {
    get: function (n) {
        ...
    },                                Jscex
    calculateAsync: eval(Jscex.compile("async", function (n) {
        var numbers = [];
        for (var i = 0; i < n; i++)
        	 numbers.push(i);
        	
        this.result = $await(make(numbers));
    }))
}                            Jscex
Jscex vs.
•
•
    •   Virtual Panel: How to Survive Asynchronous
        Programming in JavaScript

•
    •   StratifiedJS
    •   Narrative JavaScript
    •   Streamline             Jscex
Jscex vs.
•
    •
    •
    •
• Jscex
    •     JavaScript
    •
    •
Jscex vs.
•
    •
    •
    •
• Jscex
    •       JavaScript
    •       JavaScript
    •       JavaScript
Streamline

•                Jscex
    •       JavaScript
    •                    JIT
    •
•       Jscex
    •
    •   Yield – Resume vs. Asynchronous Callbacks – An
        Equivalence
Streamline (input)

var bubbleSortAsync = function (array, _) {
    for (var x = 0; x < array.length; x++) {
        for (var y = 0; y < array.length - x; y++) {
            if (compareAsync(array[y], array[y + 1], _) > 0)
                swapAsync(array, y, y + 1, _);
        }
    }
}
Streamline (compiled)
var bubbleSortAsync = function __1(array, _) {
  if (!_) {
    return __future(__1, arguments, 1);
  }                                                        if ((y < (array.length - x))) {
;                                                             return compareAsync(array[y], array[(y + 1)], __cb(_, function(__0, r) {
  var __then = _;                                               if ((r > 0)) {
  var x = 0;                                                       return swapAsync(array, y, (y + 1), __cb(_, __then));
  var __4 = false;                                              }
  return function(__break) {                                  ;
    var __loop = __nt(_, function() {                           return __then();
      var __then = __loop;                                    }));
      if (__4) {                                           }
         x++;                                                else {
      }                                                       return __break();
        else {                                             }
         __4 = true;                                     ;
      }                                                  });
    ;                                                    return __loop();
      if ((x < array.length)) {                        }(__then);
         var y = 0;                                 }
         var __3 = false;                             else {
         return function(__break) {                    return __break();
           var __loop = __nt(_, function() {        }
              var __then = __loop;                ;
              if (__3) {                          });
                 y++;                             return __loop();
              }                                 }(__then);
                else {                       };
                 __3 = true;
              }
           ;




                                                                         http://sage.github.com/streamlinejs/examples/streamlineMe.html
Jecex (input)

var bubbleSortAsync = eval(Jscex.compile("async", function (array) {
     for (var x = 0; x < array.length; x++) {
         for (var y = 0; y < array.length - x; y++) {
             var r = $await(compareAsync(array[y], array[y + 1]));
             if (r > 0)
                 $await(swapAsync(array, y, y + 1));
         }
     }
}));
Jecex (compiled)
var bubbleSortAsync = (function (array) {
    var _b_ = Jscex.builders["async"];
    return _b_.Start(this,
        _b_.Delay(function () {
            var x = 0;
            return _b_.Loop(
                function () { return x < array.length; },
                function () { x++; },
                _b_.Delay(function () {
                    var y = 0;
                    return _b_.Loop(
                        function () { return y < (array.length - x); },
                        function () { y++; }
                        _b_.Delay(function () {
                             return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) {
                                 if (r > 0) {
                                     return _b_.Bind(swapAsync(array, y, y + 1), function () {
                                          return _b_.Normal();
                                     });
                                 } else {
                                     return _b_.Normal();
                                 }
                             });
                        }),
                        false
                    );
                }),
                false
            );
        })
    );
})
Jecex (compiled)
            var bubbleSortAsync = (function (array) {
                var _b_ = Jscex.builders["async"];
                return _b_.Start(this,
                    _b_.Delay(function () {
                                                     outer loop
                        var x = 0;
                        return _b_.Loop(
                            function () { return x < array.length; },
                            function () { x++; },
                            _b_.Delay(function () {
                                var y = 0;
                                return _b_.Loop(

       inner loop                   function () { return y < (array.length - x); },
                                    function () { y++; }
                                    _b_.Delay(function () {
                                         return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) {
                                             if (r > 0) {
                                                 return _b_.Bind(swapAsync(array, y, y + 1), function () {

$await(compareAsync(...))                             return _b_.Normal();
                                                 });
                                             } else {                                $await(swapAsync(...))
                                                 return _b_.Normal();
                                             }
                                         });
                                    }),
                                    false
                                );
                            }),
                            false
                        );
                    })
                );
            })
Jscex
•
    •
    •                   “debugger”


•       JavaScript
    •   Start, Delay, Combine
    •   Loop, Try
    •   Normal, Return, Break, Continue, Throw
    •   Bind
Node.js
•
    •   JIT
    •   AOT

•
    •
    •                    Python C#
        JavaScript 1.7
    •         …
AOT
// AOT
Agent.start(eval(Jscex.compile("async", function (mailbox) {
    ...
})));

// AOT
//
//                   gzip     3kb
Agent.start((function (mailbox) {
     var _b_ = Jscex.builders["async"];
     return _b_.Start(this,
         ...
     );
}));
Jscex

•
    •           “   ”

•
//
var fib = eval(Jscex.compile("seq", function () {
    var i = 0, j = 1;
    while (true) {
        $yield(i); // the bind operation

           var t = i;
           i = j;
           j += t;
       }
}));

var iter = fib().skip(10).take(10);
while (iter.moveNext()) {
    console.log(iter.current);
}
…                   Maybe Monad
var maybeFunc = function () {
    var maybeA = getA();
    if (maybeA == Maybe.None) return Maybe.None;

	   var maybeB = getB();
    if (maybeB == Maybe.None) return Maybe.None;

    return maybeA.value + maybeB.value;
}

//
var maybeFunc = eval(Jscex.compile("maybe", function () {
     var a = $try(getA());
     var b = $try(getB());
     return a + b;
}));
•               “   ” “   ”
    •
    •
•
    •   Jscex       /
for                            Loop
function (urls) {
    for (var i = 0; i < urls.length; i++) {
        $await(requestAsync(urls[i]));
    }
}
for                                 Loop
function (urls) {
    for (var i = 0; i < urls.length; i++) {
        $await(requestAsync(urls[i]));
    }
}          function (urls) {
               var _b_ = Jscex.builders["async"];
               return _b_.Start(this,
                   _b_.Delay(function () {
                       var i = 0;
                       return _b_.Loop(
                           function () { return i < urls.length; },
                           function () { i++; },
                           _b_.Delay(function () {
                               return _b_.Bind(requestAsync(urls[i]), function () {
                                   return _b_.Normal();
                               });
                           }),
                           false
                       );
                   })
               );
           }
for
function (urls) {
    var requests = [];

    for (var i = 0; i < urls.length; i++) {
        requests.push(requestAsync(urls[i]));
    }

    $await(Jscex.Async.parallel(requests));
}
for
function (urls) {
    var requests = [];

    for (var i = 0; i < urls.length; i++) {
        requests.push(requestAsync(urls[i]));
    }
               function (urls) {
                   var _b_ = Jscex.builders["async"];
    $await(Jscex.Async.parallel(requests));
}                  return _b_.Start(this,
                       _b_.Delay(function () {

                              var requests = [];
                              for (var i = 0; i < urls.length; i++) {
                                  requests.push(requestAsync(urls[i]));
                              }

                              return _b_.Bind(Jscex.Async.parallel(requests), function () {
                                  return _b_.Normal();
                              });
                         })
                  );
              }
•       BSD

•
    •    https://github.com/JeffreyZhao/jscex
    •    http://www.sndacode.com/projects/jscex
Q &A
深入浅出Jscex

More Related Content

What's hot

Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Leonardo Borges
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기Wanbok Choi
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Leonardo Borges
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184Mahmoud Samir Fayed
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵Wanbok Choi
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185Mahmoud Samir Fayed
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!mickey24
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simplerAlexander Mostovenko
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined FunctionsChristoph Bauer
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정SeungChul Kang
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utilsroxlu
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinFabio Collini
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017Wanbok Choi
 

What's hot (20)

SDC - Einführung in Scala
SDC - Einführung in ScalaSDC - Einführung in Scala
SDC - Einführung in Scala
 
Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015Futures e abstração - QCon São Paulo 2015
Futures e abstração - QCon São Paulo 2015
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기LetSwift RxSwift 시작하기
LetSwift RxSwift 시작하기
 
YUI Tidbits
YUI TidbitsYUI Tidbits
YUI Tidbits
 
Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012Continuation Passing Style and Macros in Clojure - Jan 2012
Continuation Passing Style and Macros in Clojure - Jan 2012
 
The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184The Ring programming language version 1.5.3 book - Part 10 of 184
The Ring programming language version 1.5.3 book - Part 10 of 184
 
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
[Let'Swift 2019] 실용적인 함수형 프로그래밍 워크샵
 
The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185The Ring programming language version 1.5.4 book - Part 10 of 185
The Ring programming language version 1.5.4 book - Part 10 of 185
 
Google Guava
Google GuavaGoogle Guava
Google Guava
 
Extend R with Rcpp!!!
Extend R with Rcpp!!!Extend R with Rcpp!!!
Extend R with Rcpp!!!
 
rx.js make async programming simpler
rx.js make async programming simplerrx.js make async programming simpler
rx.js make async programming simpler
 
Apache PIG - User Defined Functions
Apache PIG - User Defined FunctionsApache PIG - User Defined Functions
Apache PIG - User Defined Functions
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 
Intro to Pig UDF
Intro to Pig UDFIntro to Pig UDF
Intro to Pig UDF
 
미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정미려한 UI/UX를 위한 여정
미려한 UI/UX를 위한 여정
 
openFrameworks 007 - utils
openFrameworks 007 - utilsopenFrameworks 007 - utils
openFrameworks 007 - utils
 
Hammurabi
HammurabiHammurabi
Hammurabi
 
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night TurinAsync code on kotlin: rx java or/and coroutines - Kotlin Night Turin
Async code on kotlin: rx java or/and coroutines - Kotlin Night Turin
 
RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017RxSwift 활용하기 - Let'Swift 2017
RxSwift 활용하기 - Let'Swift 2017
 

Similar to 深入浅出Jscex

Monadologie
MonadologieMonadologie
Monadologieleague
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsEelco Visser
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingSergey Shishkin
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSAdam L Barrett
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineRaimonds Simanovskis
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programmingMasters Academy
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Domenic Denicola
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Calvin Cheng
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changeshayato
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with ClojureDmitry Buzdin
 

Similar to 深入浅出Jscex (20)

ES6(ES2015) is beautiful
ES6(ES2015) is beautifulES6(ES2015) is beautiful
ES6(ES2015) is beautiful
 
Monadologie
MonadologieMonadologie
Monadologie
 
ES6 Overview
ES6 OverviewES6 Overview
ES6 Overview
 
TI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class FunctionsTI1220 Lecture 6: First-class Functions
TI1220 Lecture 6: First-class Functions
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Hitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional ProgrammingHitchhiker's Guide to Functional Programming
Hitchhiker's Guide to Functional Programming
 
Think Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJSThink Async: Asynchronous Patterns in NodeJS
Think Async: Asynchronous Patterns in NodeJS
 
Millionways
MillionwaysMillionways
Millionways
 
JavaScript Unit Testing with Jasmine
JavaScript Unit Testing with JasmineJavaScript Unit Testing with Jasmine
JavaScript Unit Testing with Jasmine
 
Call stack, event loop and async programming
Call stack, event loop and async programmingCall stack, event loop and async programming
Call stack, event loop and async programming
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)Functional Programming for OO Programmers (part 2)
Functional Programming for OO Programmers (part 2)
 
ECMAScript 6 major changes
ECMAScript 6 major changesECMAScript 6 major changes
ECMAScript 6 major changes
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
Scala
ScalaScala
Scala
 
FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6FalsyValues. Dmitry Soshnikov - ECMAScript 6
FalsyValues. Dmitry Soshnikov - ECMAScript 6
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Rxjs swetugg
Rxjs swetuggRxjs swetugg
Rxjs swetugg
 
Refactoring to Macros with Clojure
Refactoring to Macros with ClojureRefactoring to Macros with Clojure
Refactoring to Macros with Clojure
 
Javascript
JavascriptJavascript
Javascript
 

More from jeffz

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错jeffz
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践jeffz
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望jeffz
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望jeffz
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)jeffz
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developersjeffz
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现jeffz
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程jeffz
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得jeffz
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理jeffz
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架jeffz
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构jeffz
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性jeffz
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法jeffz
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活jeffz
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍jeffz
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持jeffz
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路jeffz
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Lifejeffz
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 

More from jeffz (20)

Wind.js无障碍调试与排错
Wind.js无障碍调试与排错Wind.js无障碍调试与排错
Wind.js无障碍调试与排错
 
JavaScript现代化排错实践
JavaScript现代化排错实践JavaScript现代化排错实践
JavaScript现代化排错实践
 
Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望Jscex:案例、阻碍、体会、展望
Jscex:案例、阻碍、体会、展望
 
Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望Jscex:案例、经验、阻碍、展望
Jscex:案例、经验、阻碍、展望
 
The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)The Evolution of Async Programming (GZ TechParty C#)
The Evolution of Async Programming (GZ TechParty C#)
 
Mono for .NET Developers
Mono for .NET DevelopersMono for .NET Developers
Mono for .NET Developers
 
单点登录解决方案的架构与实现
单点登录解决方案的架构与实现单点登录解决方案的架构与实现
单点登录解决方案的架构与实现
 
Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程Documentation Insight技术架构与开发历程
Documentation Insight技术架构与开发历程
 
Windows Phone应用开发心得
Windows Phone应用开发心得Windows Phone应用开发心得
Windows Phone应用开发心得
 
分布式版本管理
分布式版本管理分布式版本管理
分布式版本管理
 
使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架使用.NET构建轻量级分布式框架
使用.NET构建轻量级分布式框架
 
针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构针对iPad平台的高性能网站架构
针对iPad平台的高性能网站架构
 
企业开发领域的语言特性
企业开发领域的语言特性企业开发领域的语言特性
企业开发领域的语言特性
 
大话程序员可用的算法
大话程序员可用的算法大话程序员可用的算法
大话程序员可用的算法
 
面向对象与生活
面向对象与生活面向对象与生活
面向对象与生活
 
Windows内核技术介绍
Windows内核技术介绍Windows内核技术介绍
Windows内核技术介绍
 
F#语言对异步程序设计的支持
F#语言对异步程序设计的支持F#语言对异步程序设计的支持
F#语言对异步程序设计的支持
 
大众点评网的技术变迁之路
大众点评网的技术变迁之路大众点评网的技术变迁之路
大众点评网的技术变迁之路
 
Better Framework Better Life
Better Framework Better LifeBetter Framework Better Life
Better Framework Better Life
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 

Recently uploaded

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptxLBM Solutions
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 

Recently uploaded (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Key Features Of Token Development (1).pptx
Key  Features Of Token  Development (1).pptxKey  Features Of Token  Development (1).pptx
Key Features Of Token Development (1).pptx
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 

深入浅出Jscex

  • 2. / / Jeffrey Zhao / • • http://blog.zhaojie.me/ • @ • F#, JavaScript, Scala, C#, Python, .NET, Mono... • Java
  • 3. Jscex • JavaScript Computation EXpression • JavaScript • F# JavaScript • “ ” • JavaScript JavaScript
  • 4. Jscex • • Jscex JavaScript • • Jscex / • JavaScript / • ECMAScript 3
  • 5.
  • 6. var compare = function (x, y) { return x - y; } var swap = function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; } var bubbleSort = function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { if (compare(array[y], array[y + 1]) > 0) { swap(array, y, y + 1); } } } }
  • 7. var compare = function (x, y, callback) { var innerLoop = function (array, x, y, callback) { setTimeout(10, function () { if (y < array.length - x) { callback(x - y); compare(array[y], array[y + 1], function (r) { }); if (r > 0) { } swap(array, y, y + 1, function () { innerLoop(array, x, y + 1, callback); var swap = function (a, i, j, callback) { }); var t = a[i]; a[i] = a[j]; a[j] = t; } else { repaint(a); innerLoop(array, x, y + 1, callback); } setTimeout(20, callback); }); } } else { callback(); var outerLoop = function (array, x, callback) { } if (x < array) { } innerLoop(array, x, 0, function () { outerLoop(array, x + 1, callback); outerLoop(array, 0, function () { }); console.log("done!"); } else { }); callback(); } }
  • 8. var compare = function (x, y, callback) { var innerLoop = function (array, x, y, callback) { setTimeout(10, function () { if (y < array.length - x) { callback(x - y); compare(array[y], array[y + 1], function (r) { }); if (r > 0) { } swap(array, y, y + 1, function () { innerLoop(array, x, y + 1, callback); var swap = function (a, i, j, callback) { }); var t = a[i]; a[i] = a[j]; a[j] = t; } else { D repaint(a); innerLoop(array, x, y + 1, callback); } M setTimeout(20, callback); }); } } else { T callback(); var outerLoop = function (array, x, callback) { } if (x < array) { } innerLoop(array, x, 0, function () { outerLoop(array, x + 1, callback); outerLoop(array, 0, function () { }); console.log("done!"); } else { }); callback(); } }
  • 9. var compareAsync = eval(Jscex.compile("async", function (x, y) { $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms. return x - y; })); var swapAsync = eval(Jscex.compile("async", function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; // swap repaint(a); // repaint after each swap $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms. })); var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } })); http://files.zhaojie.me/jscex/samples/async/sorting-animations.html?bubble
  • 10. var compareAsync = eval(Jscex.compile("async", function (x, y) { $await(Jscex.Async.sleep(10)); // each "compare" takes 10 ms. return x - y; })); var swapAsync = eval(Jscex.compile("async", function (a, i, j) { var t = a[i]; a[i] = a[j]; a[j] = t; // swap repaint(a); // repaint after each swap $await(Jscex.Async.sleep(20)); // each "swap" takes 20 ms. })); var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } }));
  • 11. • • • • •
  • 12. Jscex // var somethingAsync = eval(Jscex.compile("async", function (...) { // } ));
  • 13. function () { var res = $await(<async work>); }
  • 14. function () { var res = $await(<async work>); } HTTP UI Web Service
  • 15. var f = eval(Jscex.compile("async", function () { var img = $await(readAsync("http://...")); console.log("loaded!"); $await(writeAsync("./files/...")); console.log("saved!"); }));
  • 16. … var f = eval('(function () { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { _b_.Bind(readAsync(...), function (img) { console.log("loaded!"); return _b_.Bind(writeAsync(...), function () { console.log("saved!"); return _b_.Normal(); }); }); }) ); })');
  • 17. … var f = (function () { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { _b_.Bind(readAsync(...), function (img) { console.log("loaded!"); return _b_.Bind(writeAsync(...), function () { console.log("saved!"); return _b_.Normal(); }); }); }) ); });
  • 18. Express var app = express.createServer(); app.get('/', function (req, res) { /** * * * 1. * 2. * * 3. res * * “ ” **/ }); app.listen(3000);
  • 19. Jscex app.getAsync('/', eval(Jscex.compile("async", function (req, res) { var keys = $await(db.getKeysAsync(...)); var results = []; for (var i = 0; i < keys.length; i++) { var r = $await(cache.getAsync(keys[i])); if (!r) { r = $await(db.getItemAsync(keys[i])); } results.push(r); } res.send(generateList(results)); })));
  • 20. I/O • I/O • Web • • • I/O •
  • 21. var getItemAsync = eval(Jscex.compile("async", function (key) { var res = $await(cache.getAsync(key)); if (res) return res; return $await(db.getItemAsync(key)); })); app.getAsync('/', eval(Jscex.compile("async", function (req, res) { var keys = $await(db.getKeysAsync(...)); // “ ” var tasks = keys.map(function (key) { return getItemAsync(key); }); // var results = $await(Jscex.Async.parallel(tasks)); res.send(generateList(results)); })));
  • 22. • • $await(Jscex.Async.parallel(taskA, taskB)) • $await(taskA.continueWith(taskB)) • $await • • • • taskA.start(); $await(taskB); $await(taskA);
  • 23. // var i = 1; conn.onAsync("data", eval(Jscex.compile("async", function () { var id = i++; $await(step1); console.log("step 1 - request " + id); $await(step2); console.log("step 2 - request " + id); /** * * step 1 - request 1 * step 1 - request 2 * step 2 - request 2 * step 2 - request 1 **/ })));
  • 24. ... the principle we go by is, don't expect to see a particular concurrency model put into C# because there're many different concurrency model ... it's more about finding things are common to all kinds of concurrency ... - Anders Hejlsberg
  • 25. Erlang var i = 0; var agent = Agent.start(eval(Jscex.compile("async", function (mailbox) { while (true) { var id = i++; var msg = $await(mailbox.receive()); $await(step1); console.log("step 1 - request " + id); $await(step2); console.log("step 2 - request " + id); } }))); conn.on("data", function (data) { // mailbox agent.send(data); });
  • 26. Jscex • JavaScript • • • • “ ”
  • 27. JavaScript • while / for / for...in / do • if / switch • try...catch...finally • return / break / continue / throw • • with • break continue • switch break •
  • 28. // var somethingAsync = eval(Jscex.compile("async", function (...) { // } ));
  • 29. eval Sample = { // compile: function (func) { return "(" + func.toString() + ")"; }, // eval compileEx: function (func) { return eval("(" + func.toString() + ")"); } }
  • 30. eval (function () { var a = 1; // f1 var f1 = eval(Sample.compile(function () { alert(a); })); f1(); // “1” // f2 Sample.compileEx var f2 = Sample.compileEx(function () { alert(a); }); f2(); // “a ” })();
  • 31. JavaScript • “bind” $await • • “ ” • “ ”
  • 32. JavaScript • • • JIT • JavaScript
  • 33. ” MyClass.prototype = { get: function (n) { ... }, calculateAsync: eval(Jscex.compile("async", function (n) { var numbers = []; for (var i = 0; i < n; i++) numbers.push(i); this.result = $await(make(numbers)); })) }
  • 34. ” MyClass.prototype = { get: function (n) { ... }, Jscex calculateAsync: eval(Jscex.compile("async", function (n) { var numbers = []; for (var i = 0; i < n; i++) numbers.push(i); this.result = $await(make(numbers)); })) } Jscex
  • 35. Jscex vs. • • • Virtual Panel: How to Survive Asynchronous Programming in JavaScript • • StratifiedJS • Narrative JavaScript • Streamline Jscex
  • 36. Jscex vs. • • • • • Jscex • JavaScript • •
  • 37. Jscex vs. • • • • • Jscex • JavaScript • JavaScript • JavaScript
  • 38. Streamline • Jscex • JavaScript • JIT • • Jscex • • Yield – Resume vs. Asynchronous Callbacks – An Equivalence
  • 39. Streamline (input) var bubbleSortAsync = function (array, _) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { if (compareAsync(array[y], array[y + 1], _) > 0) swapAsync(array, y, y + 1, _); } } }
  • 40. Streamline (compiled) var bubbleSortAsync = function __1(array, _) { if (!_) { return __future(__1, arguments, 1); } if ((y < (array.length - x))) { ; return compareAsync(array[y], array[(y + 1)], __cb(_, function(__0, r) { var __then = _; if ((r > 0)) { var x = 0; return swapAsync(array, y, (y + 1), __cb(_, __then)); var __4 = false; } return function(__break) { ; var __loop = __nt(_, function() { return __then(); var __then = __loop; })); if (__4) { } x++; else { } return __break(); else { } __4 = true; ; } }); ; return __loop(); if ((x < array.length)) { }(__then); var y = 0; } var __3 = false; else { return function(__break) { return __break(); var __loop = __nt(_, function() { } var __then = __loop; ; if (__3) { }); y++; return __loop(); } }(__then); else { }; __3 = true; } ; http://sage.github.com/streamlinejs/examples/streamlineMe.html
  • 41. Jecex (input) var bubbleSortAsync = eval(Jscex.compile("async", function (array) { for (var x = 0; x < array.length; x++) { for (var y = 0; y < array.length - x; y++) { var r = $await(compareAsync(array[y], array[y + 1])); if (r > 0) $await(swapAsync(array, y, y + 1)); } } }));
  • 42. Jecex (compiled) var bubbleSortAsync = (function (array) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { var x = 0; return _b_.Loop( function () { return x < array.length; }, function () { x++; }, _b_.Delay(function () { var y = 0; return _b_.Loop( function () { return y < (array.length - x); }, function () { y++; } _b_.Delay(function () { return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) { if (r > 0) { return _b_.Bind(swapAsync(array, y, y + 1), function () { return _b_.Normal(); }); } else { return _b_.Normal(); } }); }), false ); }), false ); }) ); })
  • 43. Jecex (compiled) var bubbleSortAsync = (function (array) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { outer loop var x = 0; return _b_.Loop( function () { return x < array.length; }, function () { x++; }, _b_.Delay(function () { var y = 0; return _b_.Loop( inner loop function () { return y < (array.length - x); }, function () { y++; } _b_.Delay(function () { return _b_.Bind(compareAsync(array[y], array[y + 1]), function (r) { if (r > 0) { return _b_.Bind(swapAsync(array, y, y + 1), function () { $await(compareAsync(...)) return _b_.Normal(); }); } else { $await(swapAsync(...)) return _b_.Normal(); } }); }), false ); }), false ); }) ); })
  • 44. Jscex • • • “debugger” • JavaScript • Start, Delay, Combine • Loop, Try • Normal, Return, Break, Continue, Throw • Bind
  • 45.
  • 47. • JIT • AOT • • • Python C# JavaScript 1.7 • …
  • 48. AOT // AOT Agent.start(eval(Jscex.compile("async", function (mailbox) { ... }))); // AOT // // gzip 3kb Agent.start((function (mailbox) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, ... ); }));
  • 49. Jscex • • “ ” •
  • 50. // var fib = eval(Jscex.compile("seq", function () { var i = 0, j = 1; while (true) { $yield(i); // the bind operation var t = i; i = j; j += t; } })); var iter = fib().skip(10).take(10); while (iter.moveNext()) { console.log(iter.current); }
  • 51. Maybe Monad var maybeFunc = function () { var maybeA = getA(); if (maybeA == Maybe.None) return Maybe.None; var maybeB = getB(); if (maybeB == Maybe.None) return Maybe.None; return maybeA.value + maybeB.value; } // var maybeFunc = eval(Jscex.compile("maybe", function () { var a = $try(getA()); var b = $try(getB()); return a + b; }));
  • 52. “ ” “ ” • • • • Jscex /
  • 53. for Loop function (urls) { for (var i = 0; i < urls.length; i++) { $await(requestAsync(urls[i])); } }
  • 54. for Loop function (urls) { for (var i = 0; i < urls.length; i++) { $await(requestAsync(urls[i])); } } function (urls) { var _b_ = Jscex.builders["async"]; return _b_.Start(this, _b_.Delay(function () { var i = 0; return _b_.Loop( function () { return i < urls.length; }, function () { i++; }, _b_.Delay(function () { return _b_.Bind(requestAsync(urls[i]), function () { return _b_.Normal(); }); }), false ); }) ); }
  • 55. for function (urls) { var requests = []; for (var i = 0; i < urls.length; i++) { requests.push(requestAsync(urls[i])); } $await(Jscex.Async.parallel(requests)); }
  • 56. for function (urls) { var requests = []; for (var i = 0; i < urls.length; i++) { requests.push(requestAsync(urls[i])); } function (urls) { var _b_ = Jscex.builders["async"]; $await(Jscex.Async.parallel(requests)); } return _b_.Start(this, _b_.Delay(function () { var requests = []; for (var i = 0; i < urls.length; i++) { requests.push(requestAsync(urls[i])); } return _b_.Bind(Jscex.Async.parallel(requests), function () { return _b_.Normal(); }); }) ); }
  • 57. BSD • • https://github.com/JeffreyZhao/jscex • http://www.sndacode.com/projects/jscex
  • 58. Q &A