Exercise 9 Solution

In notebook:
FrontEndMasters Async Javascript
Created at:
2016-09-22
Updated:
2016-09-22
Tags:
Fundamentals JavaScript
  $(document).ready(function(){
	var $btn = $("#btn"),
		$list = $("#list"),
		// 1.set up a channel for each click etc.
		// so channels instead of observables
		clicks = ASQ.csp.chan(),
		msgs = ASQ.csp.chan(),
		queuedClick; 

	$btn.click(listenToClicks);

	// run go-routines
	ASQ().runner(
		ASQ.csp.go(sampleClicks),
		ASQ.csp.go(logClick)
	);

	// push click event messages into channel
	function listenToClicks(evt){
		if (!queuedClick) {
		  // don't put in anymore clicks
		  // until the previous one has been accepted
		  // so there's only one click in the queue
		  // this simulates backpressure
		  // and we're not in a generator
		  // we DO throw away events
		  // we only use the first event
			queuedClick = ASQ.csp.putAsync(clicks,evt);
			queuedClick.then(function(){
				queuedClick = null;
			});
		}
	}

	// sample clicks channel
	function *sampleClicks() {
		while (true) {
			yield ASQ.csp.take(
				ASQ.csp.timeout(1000)
			);
			yield ASQ.csp.take(clicks);
			yield ASQ.csp.put(msgs,"clicked!");
		}
	}

	// subscribe to sampled message channel
	function *logClick() {
		while (true) {
			var msg = yield ASQ.csp.take(msgs);
			$list.append($("<div>" + msg + "</div>"));
		}
	}
});
Tells the example of how to communicate channels between different threads. For example between a browser and server. 

Browser and webworker. Spin up programmatically a webworker. The proof of concept is with webworkers that he demonstrates.

He will be able to do the same with Node, spin up child workers.