Promise Flashcards
What is a promise?
Promise represents async operatrions in javascript. Whenever you want to perform an operation that might take time and you don’t want to keep other tasks waiting for it to complete then use promise.
~~~
let callAPI=new Promise((resolve,reject)=>{
//call the API
//when API gives 200 call resolve
//Else call reject
}
callAPI.then(result=>//do something)
.catch(err=>//handle error);
~~~
Promise can be in 3 states
1. Pending
2. Resolved
3. Rejected
What is a callback function
Callback function usually gets passed as an argument to another function. Its main purpose is to be called inside the function it was passed to after certain actions.
What are server-sent events
SSE is a way of unidirection communication from Server to client. This does not require constant polling from client to server, instead client opens a connection with server so that server can send messages in certain interval.
Usages:
- Social media notifications
- Stock price updates
- Sports score updates
Methods:
- onopen: It is used when a connection to the server is opened
- onmessage: This event is used when a message is received
- onerror: It happens when an error occurs
What is RXjs?
RXjs
is a library to handle reactive programming with help of Observables. It helps handling asynchronous functionality in an efficient manner compared to promises.
Some benefits
- You can handle more than one response of stream of responses.
- Backpressure if server is sending data more than client can handle RXjs can handle such situation by negating responses or storing them in buffer
- Multithreading
- Better error handling
Difference between Promise and Observables
-
promise
can send only single value in response whileObservable
can send stream of responses -
promise
follow eager execution whileobservable
is lazy and only execute when someone subscribe to it -
promise
can not be cancelled -
Observable
support backpressure -
Observable
provide wide range of transformation capabilities such as map, filter, reduce
What are the common use cases of observables
Observables
are benficial when there can be stream of responses or responses can come frequently.
- User click events
- Push notifications from server
In above situations if you use promises then you have to continuously ask for responses.
However with Observables
you will subscribe to above events and you will get it once server sends it. In short no polling needed.
Example for user event:
import { fromEvent } from 'rxjs'; // Select the DOM element to listen for clicks on const button = document.querySelector('button'); // Create an observable that emits a value every time the button is clicked const click$ = fromEvent(button, 'click'); // Subscribe to the observable to handle the click events click$.subscribe(event => { console.log('Button clicked!', event); });
What is an event table
When you call an async function its relavant callback function needs to be stored somewhere so that it can be executed when async function has completed, this is where Event Table
comes into picture.
Event Table
is like a hashmap that stores async function and its callback as key value pairs. Once async function completes its task its callback function is picked from Event table
and pushed to event queue
What is async function?
async
function is a syntax sugar for promises
Example:
async function demo() { let response = await fetch("www.sample.com"); console.log(`${response}`); }