2023/10/12 - 10:13

Event loop
- checks if call stack is empty
- checks if there are functions in the callback queue
- moves a function from the callback queue to the call stack only when call stack is empty
- having an empty call stack doesnt mean the program ends, the program only endswhen all events are ended with an empty call stack and callback queue

If a callback requires a callback to receive data, it leads to callback hell
- nested callbacks become too deeply nested and resulting code is difficult to read, understand, maintain
- occurs when multiple asynchronous operations depend on each others' results
- each async operation depends on the result of the previous one, leading to deeply nested callbacks. as more operations are added the harder the program becomes to read and debug

Promises

- an object through which a function may propagate an error or a result sometime in the future
- at any point a promise is in one of three states
→ pending
→ resolved
→ rejected
→ sometimes “settled” - meaning it has settled on either rejected or resolved
- promise takes a function as a parameter
var promise = new Promise(func)
→ function needs a resolve and reject as arguments

Handling Errors
- promises discern data from errors with two channels of communication
- to receive a successful rsponse if and when a promise resolves, use the then() function on the promise
- to receive error details from the promise if and when it rejects, use catch()

Chaining promises
-
promise(func)
    .then(doSomething)
    .then(doSomething)
    .then(dosSomething)

- avoids callback hell by chaining them together
- when the first promise is resolved it calls the next handler... and so on. there is no limit to how many .then calls we can make

Index