Async code
3s seconds in the future the timeout is done and is echoed to the screen. We can see that the anonymous function we provide is being triggered when time has passed. Now for another more revealing example:
doWork( () => {
console.log('call me when done');
})
function doWork(cb){
setTimeout( () => {
cb();
}
Other example of callback code are events here demonstrated by a example
The gist of callbacks and async in general is that one or more methods are invoked sometime in the future, unknown when.
One word Readability
Imagine doing the following code
syncCode() // emit 1
syncCode2() // emit 2
asyncCode() // emit 3
syncCode4() // emit 4
The output could very well be
1,2,4,3
We might resort to a callback making it look like
At this point it is readable, somewhat but imagine we have only async code then it might look like:
asyncCode(() => {
asyncCode3() => {
}
})
})
Also known as callback hell
, pause for effect :)
getData()
.then(getMoreData)
This is great for Request/Response
patterns but for more advanced async scenarios I dare say only Rxjs fits the bill.