Asynchronous JavaScript Technical Paper
Published: 2023-06-01 09:33:33

# Callbacks:

What is a Callback
Function?
In JavaScript, a callback function is a function that is passed into another
function as an argument. This function can then be invoked at a later stage
of time.
Since, in JavaScript, functions are objects, functions can be passed as
arguments.

```
function printFirstName(firstname, cb){
console.log(firstname)
cb ('Rogers')
}
function printLastName(lastname) {
console.log(lastname)
}
printFirstName('Steve' printLastName )// callback
```
```
const isEven = (n)=>{
return n%2==0
}
let printResult = (evenFn, num) =>{
const isNumEven = evenFn(num)
console.log(The number ${num} is an Even Number ${isNumEven} `)
}
printResult (isEven,16)
```
> callback functions is the one of the reson to call JavaScript as the Functional programming.

# -   Promises:

## What is a Promise in JavaScript?

A  promise  in JavaScript is no different from a promise in real life. If you take a promise from me that I will bring you a bar of chocolate, there can be three cases here:

1.  You are waiting for me to come (the promise is in a  PENDING  state)
2.  I bought you a bar of chocolate (the promise is in a  FULFILLED  state)
3.  The shop was closed, or due to any reason, the promise failed ( the promise goes to the  REJECTED  state).

Similarly, when you call an  asynchronous function, i.e., a function that might send a response in the future, you are actually taking a promise. At first, the promise remains in the  PENDING  state because no response has been received. After some time, when the response is received, there are two possible cases:

1.  We got a response (i.e., the promise goes to the  FULFILLED  state)
2.  We got an error and no response (the promise got  REJECTED)

**Note:**  Getting a response means the promise is in the  SETTLED  state. In other words, the promise is not in the  PENDING  state now, and it has been either  RESOLVED  or  REJECTED.

![What is a Promise in JavaScript](https://scaler.com/topics/images/what-is-a-promise-in-javascript.webp)

:::


## How Promises Work

In technical terms, a promise is an object that is returned as a response to an asynchronous function. It can be one of these four possible states:

1.  PENDING
2.  FULFILLED
3.  REJECTED
4.  SETTLED

![promise pending and fulfilled](https://scaler.com/topics/images/promise-pending-and-fullfilled.webp)

![promise pending and rejected](https://scaler.com/topics/images/promise-pending-and-rejected.webp)

Let us understand this in a bit more detail. The moment a  promise  is invoked, it goes to the  PENDING  state and waits for a  response  to come. We might get the correct response, which makes the promise FULFILLED, or we might get an error, i.e., the promise goes to the REJECTED state. A  promise  is said to be  SETTLED  if it is not in the  pending state, i.e., either the response has arrived or an error has occurred.

**Note:**  Once settled, a promise cannot be resettled.

Code snippet

```
// Create a promise that resolves after 1 second
let promise = new Promise(function(resolve, reject) {
  setTimeout(() => resolve("done"), 1000);
});

// Chain promises together
promise.then(function(result) {
  return fetch("https://example.com/api/data");
}).then(function(response) {
  return response.json();
}).then(function(data) {
  // Do something with the data
});

// Handle errors
promise.catch(function(error) {
  // Handle the error
});
```

-   The first example creates a promise that resolves after 1 second. The  `new Promise()`  constructor takes two arguments: a function that is called when the promise is resolved or rejected, and a function that is called when the promise is rejected. In this case, the  `resolve()`  function is called after 1 second, which resolves the promise.
-   The second example chains promises together. The  `then()`  method on a promise takes a function as an argument. This function is called when the promise is resolved, and it is passed the result of the promise. In this case, the  `then()`  method is called twice. The first time, the function is called with the result of the first promise, which is the string "done". The second time, the function is called with the result of the second promise, which is the JSON data from the API.
-   The third example handles errors. The  `catch()`  method on a promise takes a function as an argument. This function is called when the promise is rejected, and it is passed the error object. In this case, the  `catch()`  method is called if the promise is rejected for any reason.

Promises are a powerful tool for asynchronous programming in JavaScript. They allow you to write code that is more concise, readable, and maintainable.

# -   Code Control:

  
Asynchronous JavaScript code control is the process of managing the execution of asynchronous JavaScript code. This can be done using a variety of techniques, including:

-   **Callbacks:**  Callbacks are functions that are passed as arguments to other functions and are called when those functions complete. This is a common technique for asynchronous code, as it allows the caller to specify what should happen when the asynchronous operation completes.
-   **Promises:**  Promises are objects that represent the outcome of an asynchronous operation. They can be used to chain together asynchronous operations and to handle errors.
-   **async/await:**  async/await are new JavaScript keywords that make it easier to write asynchronous code. They allow you to write code that looks like synchronous code, but that actually executes asynchronously.
The best technique for asynchronous JavaScript code control depends on the specific needs of the application. Callbacks are a simple and straightforward way to control asynchronous code, but they can be difficult to manage when there are multiple callbacks nested together. Promises are a more powerful tool that can be used to chain together asynchronous operations and to handle errors. async/await is the newest technique, and it offers the most concise and readable syntax for asynchronous code.

Here is an example of how to use callbacks to control asynchronous code:

Code snippet

```
function doSomethingAsync(callback) {
  // Do something asynchronous here...
  callback();
}

doSomethingAsync(function() {
  // This code will be executed when the asynchronous operation completes.
});

```




Here is an example of how to use promises to control asynchronous code:

Code snippet

```
function doSomethingAsync() {
  // Do something asynchronous here...
  return new Promise(function(resolve, reject) {
    if (somethingSuccess) {
      resolve();
    } else {
      reject();
    }
  });
}

doSomethingAsync().then(function() {
  // This code will be executed when the asynchronous operation completes successfully.
}).catch(function() {
  // This code will be executed when the asynchronous operation fails.
});

```



Here is an example of how to use async/await to control asynchronous code:

Code snippet

```
async function doSomethingAsync() {
  // Do something asynchronous here...
  const result = await something;
  // Use the result here...
}

doSomethingAsync();

```





Asynchronous JavaScript code control is an important skill for any JavaScript developer. By understanding the different techniques available, you can write code that is both efficient and easy to maintain.