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();
In this example:
- We define an
asynchronous function
delayFunction()
thatreturns
aPromise
which resolves after a delay of 2 seconds usingsetTimeout
. - We define another
asynchronous function
processDelayedResult()
which callsdelayFunction()
using await to wait for the asynchronous operation to complete. - Inside
processDelayedResult()
, we useawait
towait
for the result ofdelayFunction()
and then log the result. - Errors are caught and handled using try/catch blocks.
- Finally, we call
processDelayedResult()
to initiate the process. - This example demonstrates how
async/await
can be used to handleasynchronous
operations in a moresynchronous-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)