Open hon9g opened 5 years ago
thread
1
operation 1
thread at oncen
operation at onceconsole.log(1)
setTimeout(() => console.log("callback"), 1000)
console.log(2)
/* expeted log
* 1
* 2
* callback
*/
0 ms delay
, waiting for some request
, waiting for message from web worker
, ...
.setTimeout( () => {
console.log(1);
setTimeout ( () => {
console.log(2);
setTimeout ( () => {
console.log(3);
}, 1000);
}, 1000);
}, 1000);
const one = (f) => {
console.log(1);
setTimeout(f, 1000);
};
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
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
});
E
, one of members of the TC39
E
, something like the promise is a future(observables)
INDEX