This async/await syntax makes working with promises more straightforward and readable, especially for handling asynchronous operations in a more synchronous-looking way.
Promises are a way in JavaScript to handle asynchronous tasks, like fetching data from a server or reading files. They help you work with code that doesn't run in a predictable order.
A promise is like ordering food ,it represents something that will be delivered in the present , future or never/cancelled.
Example:
const fetchuserData = new Promise(function(resolve,reject){
setTimeout(() =>{
const data = {username :"maktub", password:"football"};
resolve(data);
}, 2000);
});
// Now, we can use the async/await syntax to work with promises more easily.
async function getUserData() {
try {
console.log("fetching user data");
const user = await fetchuserData;
console.log("user data", user);
} catch (error) {
console.error("Error", error);
}
}
getUserData();
console.log("request in progress");
Here's how the code works step by step:
The fetchUserData function returns a promise. Inside the promise, there's a setTimeout function that simulates a 2-second delay. After the delay, the promise is resolved with a JavaScript object containing user data (in this case, { username: "maktub" , password :"football" }).
The getUserData function is defined as an async function. This allows you to use the await keyword inside it.getUserData is an async function that uses await to wait for the promise to resolve. It makes the code look more like synchronous code, even though it's asynchronous.
When you call getUserData, it logs "Fetching user data..." and then waits for the promise to resolve before logging the user data.
The last console.log line runs immediately, showing that the code doesn't block while waiting for the promise.
If there were any errors during the promise resolution (for example, if you had used reject instead of resolve), the code would jump to the catch block and log the error message.
Top comments (0)