What is the difference between async and await?

Mar 24, 2024 ยท 2 min read

Asynchronous programming is essential in JavaScript to handle non-blocking operations and improve application performance. Two main techniques used for asynchronous JavaScript are async/await and promises. While they can achieve similar outcomes, there are some key differences.

Async/Await

Async/await was introduced in ES2017 and builds on top of promises. It allows you to write asynchronous code that reads similarly to synchronous code, making it easier to follow.

The async keyword is used to declare an asynchronous function. For example:

async function getUserData() {
  // await call  
}

Inside an async function you can use the await keyword before a promise-based function to pause execution until that promise settles, then returns the resolved value.

let userData = await fetchUserData();

This lets you write asynchronous code without nested callbacks or promise chains. It makes the code appear synchronous even though operations happen asynchronously behind the scenes.

Promises

Promises were introduced in ES2015 as an alternative to callback-based asynchronous code. A promise represents an operation that hasn't completed yet but is expected to in the future.

Promises can be chained together, allowing each promise to handle the async operation once the previous settles:

fetchUserData() 
  .then(user => fetchUserPosts(user)) 
  .then(posts => renderPosts(posts))

This avoids callback hell but can still be difficult to read with long promise chains.

Key Differences

While promises lay the foundation for async/await, async/await provides syntax that makes asynchronous code easier to write and maintain. It abstracts promises while still leveraging them behind the scenes.

The main advantages of async/await over promises are readability, error handling, and interoperability. Async/await results in code that is similar to synchronous code but still reaps the benefits of asynchronous execution.

Browse by tags:

Browse by language:

The easiest way to do Web Scraping

Get HTML from any page with a simple API call. We handle proxy rotation, browser identities, automatic retries, CAPTCHAs, JavaScript rendering, etc automatically for you


Try ProxiesAPI for free

curl "http://api.proxiesapi.com/?key=API_KEY&url=https://example.com"

<!doctype html>
<html>
<head>
    <title>Example Domain</title>
    <meta charset="utf-8" />
    <meta http-equiv="Content-type" content="text/html; charset=utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
...

X

Don't leave just yet!

Enter your email below to claim your free API key: