DEV Community

Cover image for Async/Await: Introduction
21 10

Async/Await: Introduction

Callbacks and promises are great when it comes to performing async operations. Promises improved over callbacks and provide a flat code syntax, especially when it comes to chaining promises. The operators on promises like allSettled, any, then and catch make it easier to write complex async operations.

Async/Await was introduced in ES7 to promote a cleaner syntax to promises. Under the hood, async/await are promises; they provide a nice abstraction layer under those keywords.

Async

async keyword could be used in front of any function (declaration, expressions, callbacks or literally anywhere). All it means is that the function will always return a promise. Any return values other than a promise will be wrapped in a resolved promise.

async function foo() {
    return "Parwinder" // returning a string but `async` will ensure it is wrapped in a promise
}

foo().then((data) => { // we can safely use then because async function foo returns a promise
    console.log(data); // Parwinder
})

We could return a promise in function foo, and it will still work. It will be unnecessary, though.

async function foo() {
    return Promise.resolve("Parwinder")
}

foo().then((data) => {
    console.log(data); // Parwinder
})

Await

await keyword makes JavaScript wait until the promise settles and returns its result. It can only be used inside an async function.

async function foo() {
    const myPromise = new Promise((resolve, reject) => {
        setTimeout(() => {
            resolve("Parwinder"); // resolves with "Parwinder" after 2 seconds
        }, 2000);
    });

    // will not move to the next line until myPromise resolves/rejects
    const name = await myPromise;
    // the execution pauses (or awaits) for the promise

    console.log(name); // Parwinder
}

foo();

As you can see in the above example await provides a cleaner syntax compared to Promise.then.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (6)

Collapse
 
pentacular profile image
pentacular β€’

It's important to note that await can also be used on non-promises, in which case it passes the value through.

This means that await can be used to resolve things that may or may not be promises.

Collapse
 
bhagatparwinder profile image
Parwinder πŸ‘¨πŸ»β€πŸ’» β€’

Yep! My async/await blog post is a 3 part series. The 3rd part discusses this. You just have to await πŸ˜‰

Collapse
 
petroskoulianos profile image
Petros Koulianos β€’

Great explanation !!!
Short and clear I like this kind of blogs 😁😁

Collapse
 
hiboabd profile image
Hibo Abdilaahi β€’

You are killing it with this series! Loving the posts πŸ™Œ

Collapse
 
bhagatparwinder profile image
Parwinder πŸ‘¨πŸ»β€πŸ’» β€’

You are far too kind. I appreciate the feedback β™₯️

Collapse
 
norrova profile image
Norro valentin β€’ β€’ Edited

Async keyword also mean the functions used inside are asynchronous ^^

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay