hon9g / TIL

Note taking on issue tab
https://github.com/hon9g/TIL/issues
1 stars 1 forks source link

Asynchronous Programming #13

Open hon9g opened 5 years ago

hon9g commented 5 years ago

INDEX

hon9g commented 5 years ago

Parallel vs. Async

sync vs. async

Single Thread

Concurrency

hon9g commented 5 years ago

Callback

console.log(1)
setTimeout(() => console.log("callback"), 1000)
console.log(2)
/* expeted log
 * 1
 * 2
 * callback
*/

callback == continuation

Callback Hell

const two = (f) => { console.log(2); setTimeout(f, 1000); };

const three = () => { console.log(3); };

one(two(three()));


- There are no observation of nesting or indentation.
- But, there are still fundamental nesting going on. 
- So, there is a Callback Hell.

## Callback Problems
#### 1. Inversion of Control
- Inversion of Control means there's a part of my program that i am in control of executing, and there's another portion of my code that I'm not in control of executing.
  - `_in control of executing:_ operations outside of callback function.`
  - `_not in control of executing:_ operations in callback function.`
- _Trust:_ 
  - not too early, 
  - not too late, 
  - not too many times, 
  - not too few times, 
  - no lost context, 
  - no swallowed errors, ... .

#### 2. Not Reasonable
#### 3. Non Fixes

## Solutions
- Async
- Promise
hon9g commented 5 years ago

Thunks

synchronous and asynchronous

const add = (a, b) => a+b;
const thunk = () => add(10, 20); // This is a synchronous thunk

thunk(); // 30
const addAsync = (a, b, callback) => setTimeout( () => callback(a+b) , 1000);
const thunk = (callback) => addAsync(10, 20, callback); // This is a asynchronous thunk

thunk(function(sum){
  console.log(sum); //30
});

Thunks and Closure

hon9g commented 5 years ago

Promise

Promise the Future value

Advantages of promise API

Promise Trust

  1. only resolved once
  2. either success OR error
  3. messages passed/kept
  4. exceptions become errors
  5. immutable once resolved
hon9g commented 5 years ago

Generators / Coroutines

hon9g commented 5 years ago

Event Reactive

(observables)