Convert Promises to Async Await

Thursday, March 16th 2023

Q: How do I convert JavaScript Promises to async/await?

In ES6, you can use the async/await syntax to write asynchronous code that looks similar to synchronous code. If you have an existing codebase that uses Promises, you can convert it to use async/await calls by wrapping the Promise code in an async function and using the await keyword to wait for the Promise to resolve.

Here's an example of how to convert a Promise chain to an async/await function:

javascript

// Original Promise code function getData() { return fetch('/data.json') .then(response => { if (!response.ok) { throw new Error('Network response was not ok'); } return response.json(); }) .then(data => { return data; }) .catch(error => { console.error('Error:', error); }); } // Converted async/await code async function getData() { try { const response = await fetch('/data.json'); if (!response.ok) { throw new Error('Network response was not ok'); } const data = await response.json(); return data; } catch (error) { console.error('Error:', error); } }

In this example, we convert a Promise chain that fetches data from a server to an async/await function. We create an async function called getData() and use the await keyword to wait for the Promise returned by fetch() to resolve. We then use an if statement to check the status of the response, and throw an error if it's not ok. We then use await again to wait for the Promise returned by response.json() to resolve, and return the data.

If there's an error at any point in the async/await function, it will be caught by a try/catch block, which will log the error to the console.

By using async/await calls, you can write asynchronous code that's easier to read and understand. However, it's important to remember that async/await functions still return Promises, so you need to use Promise.then() or Promise.catch() to handle the result of the function.