asynchronous programming Flashcards
callback function
a function passes as an argument to another function which is called after a certain task has been completed
callback hell/ pyramid of doom
multiple nested callbacks making the code hard to read an maintain
what can we use to avoid callback hell
promises
what is a promise and how does it work
a js object that links a producing and consuming code
processing is deferred to a later point in time whilst we do something else and we react once the promise has been completed
what are the three states and their results of promises
pending, undefined; initial state (waiting for something to happen)
fulfilled, value; operation successful
rejected, error; operation failed
how do nested promises work
when a promise is returned inside a callback of another promise
the outer one waits for the inner one to resolve/reject before continuing
how do we create promises
promise takes a function with two parameters; resolve and reject and the value of either will be returned once the promise finishes
how do we use (consume) a promise
we defines .then() (runs when the promise resolves) and .catch() (runs when the promise rejects)
what does parallel execution of promises do and what are the three things we can call to do this
manages promises that can run independently of each other
using promise.all(), promise.race() and promise.any()
promise.all()
takes an array of promise and returns a new promise that resolves when all promises in the array do
or rejects with the reason of the first rejected promise
promise.race()
takes an array of promises and returns a new promise that resolves/rejects as soon as one of them does not waiting for the rest
promise.any()
resolves when any of the promises resolves
if they all reject then so will any
what is the key difference between promise.any() and promise.race()
race matches the first promise whilst any must resolve
how does async and wait work
an async function implicitly returns a promise and you use await to pause the function execution until it resolves