Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Alex Reichert edited this page Jul 30, 2016 · 2 revisions

Parallelism vs Async

  • Need multiple cores to run in parallel (at the same instant)
  • What is a thread? A queue of operations that need to be performed
  • Easy to run multiple threads, but hard to coordinate
  • JS is single-threaded (just one thread processing JS)
  • But Node is multi-threaded
  • Because only one thread is processing JS, JS is asynchronous (single-threaded concurrency)
  • Is asynchrony the same as concurrency?
  • Concurrency is when two or more tasks are happening in the same period of time (NOT at exactly the same time)
  • Async as a model for concurrency
  • 'Temporal dependency' is when a program depends on another program completing first

Callbacks

  • Could also be called a "continuation"
  • "Callback hell"
  • Inversion of control
  • Code you can't trust is code you can't understand or reason about (this is why callback hell is really an issue)
  • Bugs occur when we don't understand how the program is running, e.g. the way we perceive callbacks
  • The way we express our code differs from how our brains think

Thunks

  • Function that takes no arguments because the data is already there
  • It's a function that encapsulates synchronous or asynchronous code inside
  • Useful in functional programming
  • Represents a future value that can be "unwrapped" in the future (time independent)
  • Lazy computations don't occur until they're needed (wait), eager computations occur right away (now)

Promises

  • The "promise" of a future value, similar to a thunk in that if can be "unwrapped"

Example of how to run functions in parallel:

// need to execute each function first, then chain the promises they return
var p1 = getFile('file1');
var p2 = getFile('file2');
var p3 = getFile('file3');

p1
	.then(output) // automatically returns a promise within a "then", merges with next?
	.then(function() {
		return p2;
	})
	.then(output)
	.then(function() {
		return p3;
	})
	.then(output)
	.then(function() {
		output('Complete!');
	});

Doing something similar with map/reduce:

var files = ['file1', 'file2', 'file3'];

files
	.map(getFile) // map to promises
	.reduce(function(chain, promise) {
		return chain
			.then(output)
			.then(function() {
				return promise;
			});
	}) // no initial value, so accumulator starts as first promise
	.then(function() {
		output('Complete!');
	});

Quiz

What is callback hell?

  • Inversion of control
  • Not linear in reasonability
  • The syntax limits our understanding

What is a promise?

  • A future value that can be unwrapped
  • A completion event
  • Modeling values in a time-independent way
  • A callback manager (still uses callbacks, but in a more reasonable way)

How do you pause a generator?

  • yield

How do you resume one?

  • .next()

How do we combine generators and promises for flow control?

  • TODO
Clone this wiki locally