Javascript :Understanding Async/await
By utilising async/await
, the code appears more synchronous, and we can write asynchronous code in a more sequential and readable manner
2 min readJul 5, 2023
// Example function that returns a Promise
function fetchData() {
return new Promise((resolve, reject) => {
// Simulating an asynchronous operation
setTimeout(() => {
const data = { message: "Data successfully fetched!" };
// Resolve the promise with the fetched data
resolve(data);
// Reject the promise with an error
// reject(new Error("Failed to fetch data!"));
}, 2000);
});
}
// Example asynchronous function using async/await
async function processData() {
try {
console.log("Starting the process...");
// Asynchronous operation to fetch data
const result = await fetchData();
console.log(result.message);
// Perform additional operations...
// ...
console.log("All operations complete!");
} catch (error) {
console.log("An error occurred:", error.message);
}
}
// Calling the asynchronous function
processData();
here the fetchData
` returns a simulating an asynchronous operation, The processData
function is declared as an asynchronous function using the async
keyword. Within this function, we use the await
keyword to pause the execution and wait for the fetchData
promise to resolve or reject. If the promise resolves, the result is stored in the result
variable. If the promise rejects, an error is thrown, which can be caught and handled in the catch
block….its that simple
Thank you 👋🏻