W4.1 Asynch & State - callbacks and promises Flashcards
Does JS have threads?
No
But runtime environment does have threads
What are the 2 styles of asynchronous code in JS?
- Callbacks
- Promises
What is a callback function?
A function passed by reference as a parameter - not executed immediately. It is “called back” asynchronously in the containing function’s body (usually in response to an event)
Describe the use of callbacks in a JS runtime environment
- call a function that takes a callback function and it will run asynchronously
- when the callback completes (i.e event happens) the completed task is put on a queue
- when stack is empty another thread in runtime environment (event loop) takes tasks off the queue and pushes the tasks onto the stack where they are executed (See diagram)
What is the event loop in a runtime environment?
a semi-infinite loop, polling (waiting) and blocking on the OS until something is ready - exits when there are no more events to wait on
Give examples of things that are pollable (i.e held in event loop) and things that are not (implemented by thread pool).
Pollable: - TCP/UDP sockets - http/https - stdin, stdout, stderr - timeouts - asynch DNS operations - signals Not pollable: - filesystems - DNS lookup
What is a promise in JS?
- A promise is an object representing the eventual completion or failure of an asynch operation
- a promise is a returned object that callbacks are attached to (instead of passing them into a function)
What three fields does a promise have?
- object that is promised
- function used to resolve/fulfil promise
- function used to reject promise
What three states can a promise be in?
- fulfilled
- rejected
- pending
What syntax is used for assigning fulfil/resolve and reject functions for a promise?
p.then(f, r)
where f is onFulfilled and r is onRejected.
Once promise fulfilled/rejected the respective handler function is called asynchronously.
How does promise chaining work?
- when one is fulfilled move onto the next (fulfilled promise object is returned by handler and used as the next promise’s value)
- each then leads to more asynchronous actions and promises
What is an asynchronous function?
- uses async function declaration (AsyncFunction object)
- function which executes asynchronously via the event loop, using implicit promise to return its result