001 Promises
001 Promises
PROMISES,
& REQUESTS
THE
CALL
STACK
CALL STACK
The mechanism the JS interpreter uses to keep track
of its place in a script that calls multiple functions.
Let's see...
where was I?
LAST
THING
IN...
FIRST
THING
OUT...
HOW IT WORKS
When a script calls a function, the interpreter adds it to the
call stack and then starts carrying out the function.
Any functions that are called by that function are added to
the call stack further up, and run where their calls are
reached.
When the current function is finished, the interpreter takes
it off the stack and resumes execution where it left off in
the last code listing.
isRightTriangle(3,4,5)
square(3)+square(4)
=== square(5)
square(3)
multiply(3,3)
isRightTriangle(3,4,5)
square(3)+square(4)
=== square(5)
multiply(3,3)
9
square(3)
multiply(3,3)
isRightTriangle(3,4,5)
square(3)+square(4)
=== square(5)
square(3)
9
isRightTriangle(3,4,5)
square(3)+square(4)
=== square(5)
isRightTriangle(3,4,5)
9+square(4) === square(5)
square(4)
multiply(4,4)
isRightTriangle(3,4,5)
9+square(4) === square(5)
multiply(4,4)
16
square(4)
multiply(4,4)
isRightTriangle(3,4,5)
9+square(4) === square(5)
square(4)
16
isRightTriangle(3,4,5)
9+square(4) === square(5)
isRightTriangle(3,4,5)
9+16 === square(5)
square(5)
multiply(5,5)
isRightTriangle(3,4,5)
9+16 === square(5)
multiply(5,5)
25
square(5)
multiply(5,5)
isRightTriangle(3,4,5)
9+16 === square(5)
square(5)
25
isRightTriangle(3,4,5)
9+16 === square(5)
isRightTriangle(3,4,5)
9+16 === 25
isRightTriangle(3,4,5)
true
true
JS IS
SINGLE
THREADED
WHAT DOES
THAT MEAN?
At any given point in time, that
single JS thread is running at
most one line of JS code.
Can you please send
me all movies that
match the query "Bat"
Can you please send
me all movies that
match the query "Bat"
S
BATE L
E
MOT
AN
BATM
THIS
TAKES
TIME
IS OUR APP
GOING TO
GRIND TO
A HALT?
What happens when
something takes a
long time?
Fortunately...
We have a workaround
CALLBACKS???!
THE
BROWSER
DOES THE
WORK!
TO THE
RESCUE
OK BUT HOW?
Browsers come with Web APIs that
are able to handle certain tasks in
the background (like making
requests or setTimeout)
OKEEEDOKEEE
> I print first!
> I print second!
> I print first!
Will do!
Thanks, browser!
> I print second!
Time's Up!!!
Make sure you run
that callback now!!
> I print first!