DEV Community

Cover image for How to use async/await
Anil
Anil

Posted on

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

Top comments (0)