What is the difference between async and synchronous await?

Mar 24, 2024 · 2 min read

JavaScript is inherently an asynchronous language. This means that code often does not run in the exact order it is written, especially when dealing with network requests or I/O operations. Mastering asynchronous JavaScript unlocks the ability to write complex, non-blocking applications.

The two main approaches for managing asynchronicity in JavaScript are:

  1. Callback functions
  2. The async/await syntax

Callbacks Reviewed

Callbacks are functions that are passed as arguments to other functions. They allow asynchronous code to call your code when an operation finishes:

function getUser(id, callback) {
  // fetch user from database
  callback(user); 
}

getUser(1, (user) => {
  // this runs after user is fetched
});

This works but can cause "callback hell" for complex flows.

Introducing Async/Await

The async/await syntax was introduced to simplify asynchronous code. It allows you to write asynchronous code that looks synchronous.

Functions marked with async return a Promise implicitly. Inside them you can use await to pause execution until a Promise settles.

async function getUser() {
  let user = await fetchUser(1);
  return user;
}

// Execution pauses at the await until fetchUser() fulfils

So async/await makes asynchronous code behave synchronously. But under the hood, the function keeps executing asynchronously.

Key Differences

  • Synchronous code runs in sequence – each line executes one after the other.
  • Asynchronous code allows other code to run during waits – enabling non-blocking programs.
  • So while async/await looks synchronous, it remains asynchronous and non-blocking. This makes it ideal for I/O like network requests without blocking the main thread.

    Common Pitfalls

    Take care when mixing async and synchronous code. For example, iterating over an array with .forEach will not work as expected with asynchronous calls inside it.

    Learning exactly when code yields execution back to the system takes practice. Remember, await only pauses inside async functions. The outer scope continues immediately after calling the async function.

    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: