Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

asynchronous programming in Javascript

Reference
Reference

  1. why use JavaScript Promises
  2. Explain JavaScript Promises Methods
  3. Explain JavaScript Promise Chaining
  4. Explain JavaScript Promise all and any
  5. Differences Between async and await 6.Asynchronous programming in JavaScript

Asynchronous programming in JavaScript

Asynchronous programming in JavaScript allows for the execution of code without blocking the main thread of the application. This is achieved through the use of callbacks, promises, and async/await functions.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
Enter fullscreen mode Exit fullscreen mode

In this example, the fetch method is used to make an asynchronous HTTP request to the specified API endpoint. The then method is then used to handle the response by parsing it as JSON and logging the data to the console. If an error occurs, the catch method is used to handle it by logging the error to the console.

Another example of asynchronous programming in JavaScript using async/await functions:

async function getData() {
  try {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error(error);
  }
}

getData();
Enter fullscreen mode Exit fullscreen mode

In this example, the getData function is defined as an async function, allowing it to use the await keyword to wait for the asynchronous fetch method to complete and return a response. The try...catch block is used to handle any errors that may occur during the execution of the function. The getData function is then called to initiate the asynchronous request and retrieve the data.

Image description

Image description

Image description

Image description

Here is an example of using promises to asynchronously fetch data from an API:
1.why use JavaScript Promisesclick here for solution
JavaScript Promise
Promises in real-life express a trust between two or more persons and an assurance that a particular thing will surely happen. In javascript, a Promise is an object which ensures to produce a single value in the future (when required). Promise in javascript is used for managing and tackling asynchronous operations.

Need for JavaScript Promise
Till now, we learned about events and callback functions for handling the data. But, its scope is limited. It is because events were not able to manage and operate asynchronous operations. Thus, Promise is the simplest and better approach for handling asynchronous operations efficiently.

There are two possible differences between Promise and Event Handlers:

A Promise can never fail or succeed twice or more. This can happen only once.
A Promise can neither switch from success to failure, or failure to success. If a Promise has either succeeded or failed, and after sometime, if any success/failure callback is added, the correct callback will be invoked, no matter the event happened earlier.
Terminology of Promise
A promise can be present in one of the following states:

pending: The pending promise is neither rejected nor fulfilled yet.
fulfilled: The related promise action is fulfilled successfully.
rejected: The related promise action is failed to be fulfilled.
settled: Either the action is fulfilled or rejected.
Thus, a promise represents the completion of an asynchronous operation with its result. It can be either successful completion of the promise, or its failure, but eventually completed. Promise uses a then() which is executed only after the completion of the promise resolve.

Why JavaScript promises
The getUsers() won’t work properly and always returns an empty array. Therefore, the findUser() function won’t work as expected:

function getUsers() {
  let users = [];
  setTimeout(() => {
    users = [
      { username: 'john', email: 'john@test.com' },
      { username: 'jane', email: 'jane@test.com' },
    ];
  }, 1000);
  return users;
}

function findUser(username) {
  const users = getUsers(); // A
  const user = users.find((user) => user.username === username); // B
  return user;
}

console.log(findUser('john'));
Code language: JavaScript (javascript)
Enter fullscreen mode Exit fullscreen mode

Output:

undefined

Solution:

function getUsers() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([
        { username: 'john', email: 'john@test.com' },
        { username: 'jane', email: 'jane@test.com' },
      ]);
    }, 1000);
  });
}

function onFulfilled(users) {
  console.log(users);
}

const promise = getUsers();
promise.then(onFulfilled);
Enter fullscreen mode Exit fullscreen mode

Code language: JavaScript (javascript)
Output:


[
{ username: 'john', email: 'john@test.com' },
{ username: 'jane', email: 'jane@test.com' }
]

Image description

2.Explain JavaScript Promises Methodsclick here for solution
Image description

<html>
<head>
<h2> Javascript Promise</h2>
</br> </head>
<body>
<script>
var p=new Promise(function(resolve, reject){
var x= 2+3;
if(x==5)
    resolve(" executed and resolved successfully");
else
    reject("rejected");
});
 p.then(function(fromResolve){
 document.write("Promise is"+fromResolve);
 }).catch(function(fromReject){
 document.write("Promise is "+fromReject);
 });
</script>
</body>
</html>

Enter fullscreen mode Exit fullscreen mode

** output:**
Promise is executed and resolved successfully

To make the code more concise, you can use an arrow function as the argument of the then() method like this:

function getUsers() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      resolve([
        { username: 'john', email: 'john@test.com' },
        { username: 'jane', email: 'jane@test.com' },
      ]);
    }, 1000);
  });
}

const promise = getUsers();

promise.then((users) => {
  console.log(users);
});
Enter fullscreen mode Exit fullscreen mode

Code language: JavaScript (javascript)
Because the getUsers() function returns a promise object, you can chain the function call with the then() method like this:

// getUsers() function
//...

getUsers().then((users) => {
  console.log(users);
});
Enter fullscreen mode Exit fullscreen mode
let success = true;

function getUsers() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success) {
        resolve([
          { username: 'john', email: 'john@test.com' },
          { username: 'jane', email: 'jane@test.com' },
        ]);
      } else {
        reject('Failed to the user list');
      }
    }, 1000);
  });
}

function onFulfilled(users) {
  console.log(users);
}
function onRejected(error) {
  console.log(error);
}

const promise = getUsers();
promise.then(onFulfilled, onRejected);
Enter fullscreen mode Exit fullscreen mode

2) The catch() method

promise.catch(onRejected);

let success = false;

function getUsers() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      if (success) {
        resolve([
          { username: 'john', email: 'john@test.com' },
          { username: 'jane', email: 'jane@test.com' },
        ]);
      } else {
        reject('Failed to the user list');
      }
    }, 1000);
  });
}

const promise = getUsers();

promise.catch((error) => {
  console.log(error);
});
Enter fullscreen mode Exit fullscreen mode

3) The finally() method

const render = () => {
  //...
};

getUsers()
  .then((users) => {
    console.log(users);
  })
  .catch((error) => {
    console.log(error);
  })
  .finally(() => {
    render();
  });
Enter fullscreen mode Exit fullscreen mode

3.Explain JavaScript Promise Chainingclick here for solution

you want to execute two or more related asynchronous operations, where the next operation starts with the result from the previous step. For example:

let p = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve(10);
    }, 3 * 100);
});

p.then((result) => {
    console.log(result); // 10
    return result * 2;
}).then((result) => {
    console.log(result); // 20
    return result * 3;
}).then((result) => {
    console.log(result); // 60
    return result * 4;
});
Code language: JavaScript (javascript)
Output:

10
20
60
Enter fullscreen mode Exit fullscreen mode
function getUser(userId) {
    return new Promise((resolve, reject) => {
        console.log('Get the user from the database.');
        setTimeout(() => {
            resolve({
                userId: userId,
                username: 'admin'
            });
        }, 1000);
    })
}

function getServices(user) {
    return new Promise((resolve, reject) => {
        console.log(`Get the services of ${user.username} from the API.`);
        setTimeout(() => {
            resolve(['Email', 'VPN', 'CDN']);
        }, 3 * 1000);
    });
}

function getServiceCost(services) {
    return new Promise((resolve, reject) => {
        console.log(`Calculate the service cost of ${services}.`);
        setTimeout(() => {
            resolve(services.length * 100);
        }, 2 * 1000);
    });
}
Code language: JavaScript (javascript)
The following uses the promises to serialize the sequences:

getUser(100)
    .then(getServices)
    .then(getServiceCost)
    .then(console.log);
Enter fullscreen mode Exit fullscreen mode

Code language: CSS (css)
Output

Get the user from the database.
Get the services of admin from the API.
Calculate the service cost of Email,VPN,CDN.
300

4.Explain JavaScript Promise all and anyclick here for solution
The Promise.all() static method takes an iterable of promises:

Promise.all(iterable);
Code language: JavaScript (javascript)
The Promise.all() method returns a single promise that resolves when all the input promises have been resolved. The returned promise resolves to an array of the results of the input promises:

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('The first promise has resolved');
    resolve(10);
  }, 1 * 1000);
});
const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('The second promise has resolved');
    resolve(20);
  }, 2 * 1000);
});
const p3 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('The third promise has resolved');
    resolve(30);
  }, 3 * 1000);
});

Promise.all([p1, p2, p3]).then((results) => {
  const total = results.reduce((p, c) => p + c);

  console.log(`Results: ${results}`);
  console.log(`Total: ${total}`);
});
Enter fullscreen mode Exit fullscreen mode

Code language: JavaScript (javascript)
Output

The first promise has resolved
The second promise has resolved
The third promise has resolved
Results: 10,20,30
Total: 60

Introduction to JavaScript Promise.any() method
The Promise.any() method accepts a list of Promise objects as an iterable object:

Promise.any(iterable);
Code language: JavaScript (javascript)
If one of the promises in the iterable object is fulfilled, the Promise.any() returns a single promise that resolves to a value which is the result of the fulfilled promise:

const p1 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('Promise 1 fulfilled');
    resolve(1);
  }, 1000);
});

const p2 = new Promise((resolve, reject) => {
  setTimeout(() => {
    console.log('Promise 2 fulfilled');
    resolve(2);
  }, 2000);
});

const p = Promise.any([p1, p2]);
p.then((value) => {
  console.log('Returned Promise');
  console.log(value);
});
Enter fullscreen mode Exit fullscreen mode

Code language: JavaScript (javascript)
Output:

Promise 1 fulfilled
Returned Promise
1
Promise 2 fulfilled

5.Differences Between async and awaitclick here for solution
JavaScript Async
An async function is a function that is declared with the async keyword and allows the await keyword inside it. The async and await keywords allow asynchronous, promise-based behavior to be written more easily and avoid configured promise chains. The async keyword may be used with any of the methods for creating a function.
Suppose that you need to perform three asynchronous operations in the following sequence:

Select a user from the database.
Get services of the user from an API.
Calculate the service cost based on the services from the server.
The following functions illustrate the three tasks. Note that we use the setTimeout() function to simulate the asynchronous operation.

here we use promise Chaining
First, you need to return a Promise in each function:

function getUser(userId) {
    return new Promise((resolve, reject) => {
        console.log('Get user from the database.');
        setTimeout(() => {
            resolve({
                userId: userId,
                username: 'john'
            });
        }, 1000);
    })
}

function getServices(user) {
    return new Promise((resolve, reject) => {
        console.log(`Get services of  ${user.username} from the API.`);
        setTimeout(() => {
            resolve(['Email', 'VPN', 'CDN']);
        }, 2 * 1000);
    });
}

function getServiceCost(services) {
    return new Promise((resolve, reject) => {
        console.log(`Calculate service costs of ${services}.`);
        setTimeout(() => {
            resolve(services.length * 100);
        }, 3 * 1000);
    });
}
Code language: JavaScript (javascript)
Then, you chain the promises:

getUser(100)
    .then(getServices)
    .then(getServiceCost)
    .then(console.log);
Enter fullscreen mode Exit fullscreen mode

introduced the async/await keywords that build on top of promises, allowing you to write asynchronous code that looks more like synchronous code and is more readable. Technically speaking, the async / await is syntactic sugar for promises.

If a function returns a Promise, you can place the await keyword in front of the function call, like this:

let result = await f();
Code language: JavaScript (javascript)
The await will wait for the Promise returned from the f() to settle. The await keyword can be used only inside the async functions.

The following defines an async function that calls the three asynchronous operations in sequence:

async function showServiceCost() {
    let user = await getUser(100);
    let services = await getServices(user);
    let cost = await getServiceCost(services);
    console.log(`The service cost is ${cost}`);
}

showServiceCost();
Enter fullscreen mode Exit fullscreen mode

Top comments (0)