DEV Community

Afi0125
Afi0125

Posted on • Updated on

Async and Await function in JavaScript Promises

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");
Enter fullscreen mode Exit fullscreen mode

Image description

Here's how the code works step by step:

  1. 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" }).

  2. 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.

  3. When you call getUserData, it logs "Fetching user data..." and then waits for the promise to resolve before logging the user data.

  4. The last console.log line runs immediately, showing that the code doesn't block while waiting for the promise.

  5. 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)