Promises, Async, and Await
promise is an object
representing eventual completion or failure of an asynchronous operation.
async & await
async functions are the functions that returns promise, async function uses
await keyword inside them.
await keywords used inside the async function to pause the execution until the
promise is resolved or rejected.
async makes a function return a Promise
await makes a function wait for a Promise
async function fetchData() {
let promise = new
Promise((resolve, reject) => {
setTimeout(()
=> {
console.log("resolved");
resolve("Data
received"); // Resolving the promise
}, 1000);
});
try {
let data = await
promise; // Awaiting the previously created promise
console.log(data); // "Data received"
} catch (error) {
console.error(error); // Handles any errors
}
}
fetchData();
No comments:
Post a Comment