/
/
What Is Async Await In JavaScript?
Share on facebook
Share on twitter
Share on linkedin
Share on whatsapp
Share on email

What Is Async Await In JavaScript?

Async await the new step in the evolution of handling asynchronous operations in JavaScript. They are simple words, but their power can be used to do very complex tasks.🏆

It gives you two new keywords to use in your code: “async” and “await.”🤔
Async is for declaring that a function will handle asynchronous operations, and await used to declare that we want to “await” the result of an asynchronous operation inside a function with the async keyword.👋

Async functions return a Promise. 🙋

✔️ – If the function throws an error, the Promise will be rejected.

❌ – If the function returns a value, the Promise will be resolved.

🚀 How it works 🚀

There are Async Functions. These are declared by prepending the word async before their declaration.

⚡️Your code can be paused waiting for an Async Function with await.

⚡️Await returns whatever the async function returns when it is done.

⚡️Await can only be used inside an async function.

⚡️Functions just like in normal JS and can be caught with try/catch.

⚡️If an async function throws an exception, the exception will bubble up to the parent.

const getProjectsByUsername = async username => {
    try {
        const userResponse = await axios.get(`/api/user?username=${username}`)
        const user = userResponse.data
        const projectsResponse = await axios.get(`/api/user/${user.id}/projects`)
        return projectsResponse.data
    } catch (err) {
        console.log(err);
    }
};

getProjectsByUsername('Ron') // Return example 👇

// Output: 👉 [
//     { projectName: 'ToDoClick', title: 'Create your Tasks with one click' },
//     { projectName: 'NetflixClone', title: 'build Netflix like app' },
// ];

📚 Async/await – Key Points.

  • Async/await is a new way to write asynchronous code.
  • Async/await is actually just syntax sugar built on top of promises.

Conclusion 🎁

Async Await is a JavaScript construct that allows your code to look synchronous but still execute asynchronously. Developers need to know how this works because it can make debugging easier when working with asynchronous events in the browser and makes coding more efficient by reducing the number of callback functions needed.

Recent Snippet

How to use reduce over an array of objects

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.

How to get the highest or the lowest value in an array

To get the maximum or the minimum value from an array, we can use Math.max() and pass as arguments the numbers from which we want to pick.