Async/await in JavaScript
Async/await
76
Async/await is a feature in JavaScript that allows developers to write asynchronous code that looks and behaves more like synchronous code. This makes it easier to write and reason about asynchronous logic, and helps avoid issues like callback hell and race conditions.
In essence, the async
keyword is used to designate a function as asynchronous, and the await
keyword is used to indicate that the function should wait for a Promise to resolve before continuing (much like the yield
keyword in a generator function). This allows for more natural, sequential code flow that is easier to read and debug.
Here's a simple example of using async/await:
async function getUsers() { const response = await fetch('https://jsonplaceholder.typicode.com/users'); const data = await response.json(); return data; } getUsers().then(users => { console.log(users); });
In this example, getUsers()
is marked as an asynchronous function with the async
keyword. Within the function, fetch()
is used to retrieve data from an external API. The await
keyword is used to wait for the Promise returned by fetch()
to resolve, and then the JSON data is extracted and returned.
Finally, getUsers()
is called and the returned Promise is handled with a .then()
method to log the user data to the console.
Async/await is a powerful tool for writing more readable, maintainable asynchronous code in JavaScript.
March 25, 2023