JavaScript
Beyond The Dent
Asynchronous JavaScript
WHO IS THIS GUY?
Amit Jain
Front-end engineer, CSS, HTML , JavaScript junkie and web lover.
Senior Engineer UI @ inmobi.com
PLEASE ASK QUESTIONS
- If anything isn’t clear
- If you want to know more about something
- If I don’t know I can find out for you :)
THE FLEXIBILITY OF JAVASCRIPT
One of the most powerful features of the language is its flexibility. As a JavaScript programmer, you can make your programs as simple or as complex as you wish them to be
WHAT I’M GOING TO TALK ABOUT
& How to solve complex Async problems using These /\ methods
Loops
ASYNC JS & It's Issues
- Race Conditions
- Memory Leaks
- Complex State Machines
- Uncaught Async Errors
Events and Arrays are both
collections
we can program them the same way
Iterator
var iterator = [1,2,3].iterator();
console.log(iterator.next())
{ value: 1, done: false }
console.log(iterator.next())
{ value: 2, done: false }
console.log(iterator.next())
{ value: 3, done: false }
console.log(iterator.next())
{ done: ture }
Observer Pattern
Text
document.addEventListener(
“mousemove”,
function next(e) {
console.log(e);
});
);
{ clientX: 425, clientY: 543 }
{ clientX: 536, clientY: 123 }
{ clientX: 267, clientY: 239 }
Iterator -- progressively send information to consumer -- Observer
The Iterator and Observer Pattern are Symmetrical
Observer --|-- Interator
Iterator
Iterator object request from producer.
Consumer pulling the value one item a time
(Consumer in control )
Observer
Observer pushes info one item a time.
Observer pattern producer iterates you,
(Producer in control)
Push APIs
- DOM Events
- Websockets
- Server-sent Events
- Node Streams
- Service Workers
- XMLHttpRequest
- setInterval
Introducing Observable
- Observable === Collection +(over) Time
- Gives an object which represent that stream
Observable cont..
- Observable are lazy.
- You can not pull a value from observable like sync pull a value out of array with index.
- Observable are very cheap to make copies as they don't store items in memory not collecting item in memory, they forward to call backs.
- Unlike for loop foreach can run asynchronously.
Observables can model..
- Events
- Async Server Requests
- Animations
var mouseMoves =
Observable.
fromEvent(element, “mousemove”);
// “subscribe”
var subscription =
mouseMoves.forEach({
onNext: event => console.log(event), // error
onError: error => console.error(error),// completed
onCompleted: () => console.log(“done”)
});
// “unsubscribe”
subscription.dispose();
var clicks = Observable.fromEvent(button, 'click');
var points =
clicks.map(function(e) {
return {x: e.clientX, y: e.clientY};
});
var drags =
mouseDowns.
map(function(e) {
return MouseMoves.
takeUntil(MouseUps);
}).
concatAll();
DO I NEED A HELMET ?
Questions & Answers!
THANK YOU.
JavaScript - Beyond The Dent
By Amit Jain
JavaScript - Beyond The Dent
JS
- 505