DEV Community

Cover image for How to use async/await
Anil
Anil

Posted on

3

How to use async/await

Here's a smaller example demonstrating the use of async/await with a simple asynchronous function:

async function delayFunction() {
  return new Promise(resolve => {
    setTimeout(() => {
      resolve('Async operation complete');
    }, 2000); 
  });
}
 result
async function processDelayedResult() {
  try {
    const result = await delayFunction();
    console.log(result);
  } catch (error) {
    console.error('Error processing delayed result:', error);
  }
}
processDelayedResult();

Enter fullscreen mode Exit fullscreen mode

In this example:

  1. We define an asynchronous function delayFunction() that returns a Promise which resolves after a delay of 2 seconds using setTimeout.
  2. We define another asynchronous function processDelayedResult() which calls delayFunction() using await to wait for the asynchronous operation to complete.
  3. Inside processDelayedResult(), we use await to wait for the result of delayFunction() and then log the result.
  4. Errors are caught and handled using try/catch blocks.
  5. Finally, we call processDelayedResult() to initiate the process.
  6. This example demonstrates how async/await can be used to handle asynchronous operations in a more synchronous-looking and readable manner.

Array methods in react.js
Fragment in react.js
Conditional rendering in react.js
Children component in react.js
use of Async/Await in react.js
Array methods in react.js
JSX in react.js
Event Handling in react.js
Arrow function in react.js
Virtual DOM in react.js
React map() in react.js
How to create dark mode in react.js
How to use of Props in react.js
Class component and Functional component
How to use of Router in react.js
All React hooks explain
CSS box model
How to make portfolio nav-bar in react.js

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay