Skip to content

Basic

  1. JS is synchronous by default
  2. normal function has global scope
  3. arrow and anonymous function doesnt have global scope

Async Programming

  1. JavaScript runs code sequentially in top-down order. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.
  2. Functions running in parallel with other functions are called asynchronous. example :- setTimeout()

CallBack

  1. A function that is passed to another function as a parameter is a callback
  2. the way to create a callback is to pass it as a parameter to another function
  3. Instead of passing the name of a function as an argument to another function, you can always pass a whole function instead:
setTimeount(functionName,3000);
setTimeout(function(){
    console.log('this is callback function');
},3000);

function functionName(){
     console.log('this is callback function');
}
  1. A callback function can run after another function has finished
  2. When you pass a function as an argument, remember not to use parenthesis.

setTimeout:

  1. it is an inbuilt function in JS
  2. is called as blocking code - holding execution for time
  3. which calls a function or evaluates an expression after a given period of time
  4. setTimeout function takes a callback function as first parameter, and time in millisecond as second parameter.
The syntax:

let timerId = setTimeout(func|code, [delay], [arg1], [arg2], ...)
 // A call to setTimeout returns a “timer identifier” timerId that we can use to cancel the execution as below.

 clearTimeout(timerId);



function sayHi(phrase, who) {
    alert( phrase + ', ' + who );
}
setTimeout(sayHi, 1000, "Hello", "John"); // Hello, John

 Example 2---------

function loadScript(src, callback) {
let script = document.createElement('script');
script.src = src;
script.onload = () => callback(script);
document.head.append(script);
}

loadScript('https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.2.0/lodash.js', script => {
alert(`Cool, the script ${script.src} is loaded`);alert( \_ ); // function declared in the loaded script
});
  1. setTimeout Vs setInterval
  2. setTimeout allows us to run a function once after the interval of time.
  3. setInterval allows us to run a function repeatedly, starting after the interval of time, then repeating continuously at that interval.

callStack :

  1. is basically a going to track execution of function main agenda of callstack is to execute function
  2. The queue is first-in-first-out: tasks enqueued first are run first. Execution of a task is initiated only when nothing else is running. Or, to put it more simply, when a promise is ready, its .then/catch/finally handlers are put into the queue; they are not executed yet. When the JavaScript engine becomes free from the current code, it takes a task from the queue and executes it. 3.The two problems that we faced in callbacks are:- 1. Callback Hell: Asynchronous operations in JavaScript can be achieved through callbacks. Whenever there are multiple dependent Asynchronous operations it will result in a lot of nested callbacks. This will cause a 'pyramid of doom' like structure. 2. Inversion of control: When we give the control of callbacks being called to some other API, this may create a lot of issues. That API may be buggy, written by interns, may not call our callback and create order as in the above example, may call the payment callback twice etc.

WEB API

basically deals with execution of blocking code

CallBack Queue:

  1. it monitors the Asynchronous function

Event Loop :

  1. is middle person who checks if call stack is empty or not
  2. if callstack is empty then it pushesh function in callback queue to call stack for execution + event loop comes in, which makes sure your asynchronous code runs after all the synchronous code is done executing.

Callback:

  1. is a a function which takes one more function as parameter

“callback hell” or “pyramid of doom :

  1. The “pyramid” of nested calls grows to the right with every asynchronous action. Soon it spirals out of control.
  2. We can try to alleviate the problem by making every action a standalone function

write callback hell code

```setTimeout(()=>{ console.log("1") setTimeout(()=>{ console.log("nested timeout") throw new Error('Parameter is not a number!'); // if error happens here then there is no gurantee that below code will execute setTimeout(()=>{ console.log("super nested callback") },1000) },1000) },1000)

---

or

---

loadScript('1.js', function(error, script) {

if (error) { handleError(error); } else { // ... loadScript('2.js', function(error, script) { if (error) { handleError(error); } else { // ... loadScript('3.js', function(error, script) { if (error) { handleError(error); } else { // ...continue after all scripts are loaded (*) } });

  }
});

} });

We can try to alleviate the problem by making every action a standalone function, like this:

loadScript('1.js', step1);

function step1(error, script) { if (error) { handleError(error); } else { // ... loadScript('2.js', step2); } }

function step2(error, script) { if (error) { handleError(error); } else { // ... loadScript('3.js', step3); } }

function step3(error, script) { if (error) { handleError(error); } else { // ...continue after all scripts are loaded (*) } }

# Promise

1. Before promises, callbacks were used to handle asynchronous operations. But due to limited functionality of callback, using multiple callbacks to handle asynchronous code can lead to unmanageable code.
2. A JavaScript Promise object contains both the producing code and calls to the consuming code:
3. The function passed to new Promise is called the executor.
4. Its arguments myResolve and myReject are callbacks provided by JavaScript itself. Our code is only inside the executor.
5. When the executor obtains the result, be it soon or late, doesn’t matter, it should call one of these callbacks:
   1. resolve(value) — if the job is finished successfully, with result value.
   2. reject(error) — if an error has occurred, error is the error object.

let myPromise = new Promise(function(myResolve, myReject) { // "Producing Code" (May take some time) // your code goes here

myResolve(); // when successful myReject(); // when error });

// "Consuming Code" (Must wait for a fulfilled Promise) myPromise.then( function(value) { /_ code if successful / }, function(error) { / code if some error _/ } );

2. The Promise object supports two properties: state and result.
3. myPromise.state Vs myPromise.result
   1. "pending" => undefined => initially. Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
   2. "fulfilled" => a result value => when value is called. This state represents that the promise has been fulfilled, meaning the async operation is completed.
   3. "rejected" => an error object => when error is called - This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
   4. " Settled " => This state represents that the promise has been either rejected or fulfilled.
4. You cannot access the Promise properties state and result.
5. `resolve()` is a function that will be called, when the async operation has been successfully completed.
6. `reject()` is a function that will be called, when the async operation fails or if some error occurs.
7. `then()` method is used to access the result when the promise is fulfilled.
8. `catch()` method is used to catch exception when the promise is rejected.

9. You must use a Promise method to handle promises. using .then()
   1. Promise.then() takes two arguments, a callback for success and another for failure.
   2. Both are optional, so you can add a callback for success or failure only.

myPromise.then( function(value) { /_ code if successful / }, function(error) { / code if some error _/ } );

3. Also, resolve/reject expect only one argument (or none) and will ignore additional arguments.
4. There can be only a single result or an error
5. All further calls of resolve and reject are ignored:

let promise = new Promise(function(resolve, reject) { resolve("done"); reject(new Error("…")); // ignored setTimeout(() => resolve("…")); // ignored });

# Promise Methods

1. <mark>Promise.all(promises)</mark> – waits for all promises to resolve and returns an array of their results. If any of the given promises rejects, it becomes the error of Promise.all, and all other results are ignored.
2. <mark>Promise.allSettled(promises)</mark> waits for all promises to settle and returns their results as an array of objects with:
   status: "fulfilled" or "rejected"
   value (if fulfilled) or reason (if rejected).
3. <mark>Promise.race(promises)</mark> = – waits for the first promise to settle, and its result/error becomes the outcome.
4. <mark>Promise.any(promises)</mark> = waits for the first promise to fulfill, and its result becomes the outcome.
5. <mark>Promise.any(promises)</mark>

# Promises chaining

1. The whole thing works, because every call to a .then returns a new promise, so that we can call the next .then on it.
2. When a handler returns a value, it becomes the result of that promise, so the next .then is called with it.

new Promise(function(resolve, reject) {

setTimeout(() => resolve(1), 1000); // (*)

}).then(function(result) { // (**)

alert(result); // 1 return result * 2;

}).then(function(result) { // (***)

alert(result); // 2 return result * 2;

}).then(function(result) {

alert(result); // 4 return new Promise((resolve, reject) => { // (_) setTimeout(() => resolve(result _ 2), 1000); });

//Returning promises allows us to build chains of asynchronous actions.

});

# Async , await

1. The await keyword can only be used inside an async function.
2. The word “async” before a function means one simple thing: a function always returns a promise. Other values are wrapped in a resolved promise automatically.
- Async / await syntax is used to simpplify working with promises.It allows you to write asynchronous code that looks like synschronous code, Making it easier to read and maintain.
Async keyword defines function as asynchronous while wait keyword inside function indicates to wait for promise to resolve or reject 
3. If we try to use await in a non-async function, there would be a syntax error:

async function f() { return 1; }

f().then(alert); // 1

// ---------------- is same as

async function f() { return Promise.resolve(1); }

f().then(alert); // 1

1. he keyword await makes JavaScript wait until that promise settles and returns its result.

# fetch()

1. .
   `let promise = fetch(url);`
2. `response.text():` = To read the full response, we should call the method response.text(): it returns a promise that resolves when the full text is downloaded from the remote server, with that text as a result.
3. `response.json()` = reads the remote data and parses it as JSON.
4. .then passes results/errors to the next .then/catch.

---

---

promises + Promise and it’s state
what is promise
what are states of promise
how to write a promose
Accessing values
promise chaining
promise.all();
`Promise.all([promises])` accepts a collection (for example, an array) of promises as an argument and executes them in parallel.
This method waits for all the promises to resolve and returns the array of promise results. It rejects if any of the promises reject with the first rejection
The Promise.any():
`Promise.any([promises])` - Similar to the all() method, .any() also accepts an array of promises to execute them in parallel. This method doesn't wait for all the promises to resolve. It is done when any one of the promises is resolved or all are rejected.
The Promise.allSettled()
`promise.allSettled([promises])` - This method waits for all promises to settle(resolve/reject) and returns their results as an array of objects. The results will contain a state (fulfilled/rejected) and value, if fulfilled. In case of rejected status, it will return a reason for the error.
`The Promise.race()` method
Promise.race([promises]) – It waits for the first (quickest) promise to settle whether resolved or rejected, and returns the result/error accordingly.
https://www.freecodecamp.org/news/javascript-promise-tutorial-how-to-resolve-or-reject-promises-in-js/

- Promise vs async await

```