JavaScript: Async and Request
Tags: javascript, beginners
Published: 2022-09-15 23:46:42

1. JavaScript is a single-thread language. But the event loop allows it to run asynchronous code.
2. The event loop has four parts: memory heap, call stack, event queue and event loop.
 * The heap stores the variable and object currently in use. 
 * The call stack tracks the function that's currently running. When a function is invoked, a frame is added to the call stack in a LIFO(last in first out) order. 
 * The messages returned from API will be sent to wait in the queue.
 * And the event loop always brings the first message to the stack if the stack is empty.
 **Note**: setTimeout() is a Node function which delays the execution of a callback function using the event-loop.
3. Promises are objects that represent the eventual outcome of an asynchronous operation. A promise can have three states: pending, fulfilled, rejected.A promise is settled if it is either resolved or rejected.
 * Example of a promise is handled by two callback functions

```
const handleSuccess = (res) => {
    console.log(res);
}
const handleFailure = (rej) => {
    console.log(rej);
}
const checkNum = (num) => {
    return new Promise((resolve, reject) => {
        if (num > 2) {
            resolve('this num is larger than 2');
        }
        else {
            reject('this num is less than 2');
        };
    })
};
checkNum(5).then(handleSuccess).catch(handleFailure);
// output: this num is larger than 2
```
  * `.then(handleSuccess,handleFailure)` is equal to `.then(handleSuccess).catch(handleFailure)`

4.When three functions are independent, use `Promise.all([fun1, fun2, fun3])`
<hr>

1. The `async` keyword is used to write functions with asynchronous actions. Async functions will always return a promise. 

```
const exampleFunction = async ()=>{
    return 5
}
exampleFunction()
.then((res)=>{
    console.log(res)
})
.catch((rej)=>{
    console.log(rej)
})
//Output: 5
```
2.`await` halts the execution of a function until a given promise is resolved. If a promise is still pending, the log result will be pending promise.
3.try{}catch(err){console.log(err)} can be used to handle error.
4.When multiple functions can happen simultaneously, use `await Promise.all()`. The resolved value is an array with all the resolved promise from the argument array. The soon as one promise is rejected, it rejects and returns the reject reason from that promise.
```
async function asyncPromAll() {
  const resultArray = await Promise.all([asyncTask1(), asyncTask2(), asyncTask3(), asyncTask4()]);
  for (let i = 0; i<resultArray.length; i++){
    console.log(resultArray[i]); 
  }
}
```
<hr>
1. fetch url is made by `${baseUrl}${endPoint}${requestParams}`
2. GET request

```
fetch('http://api-to-call.com/endpoint')
.then(response => {
  if (response.ok) {
    return response. json();
  }
  throw new Error('Request failed!');
}, networkError => console.log(networkError.message)
). then (isonResponse => {
// Code to execute with isonResponse
};
```
or 

```
const getData = async () => {
    try {
        const response = await fetch('https://api-to-call.com/endpoint');
        if (response.ok) {
            const jsonResponse = await response.json();
            //code to do with response
        }
        throw new Error('Request failed!');
    } catch (error) {
        console.log(error);
    }
}
```

3.POST request

```
fetch('http: //api-to-call.com/endpoint', {
    method: 'POST',
    body: JSON.stringify({ id: '200' })
}).then(response => {
    if (response.ok) {
        return response.ison();
    }
    throw new Error('Request failed!');
}, networkError => console.log(networkError.message)
).then(jsonResponse => {
    // Code to execute with isonResponse
});
```
or 

```
const getData = async () => {
    try {
        const response = await fetch('https://api-to-call.com/endpoint', {
            method: 'POST',
            body: JSON.stringify({ id: 200 })
        });
        if (response.ok) {
            const jsonResponse = await response.json();
            //code to do with response
        }
        throw new Error('Request failed!');
    } catch (error) {
        console.log(error);
    }
}
```
[Resource referenced: Codecademy.com](https://www.codecademy.com/learn)