DEV Community

Cover image for Beginners guide to async-await in Javascript
Ashok Naik
Ashok Naik

Posted on • Edited on

2 1

Beginners guide to async-await in Javascript

Async Await is syntactical sugar wrapped around to make the implementation of promises easier, If you don't understand how promises works make sure you check out this post

The purpose of async / await is to simplify the syntax necessary to consume promise-based APIs.

Let's jump into an example that will help us understand Async Await in a better way.

function newRequest(place) {
    return new Promise((resolve,reject)=>{
    if(place === 'home') {
    resolve('You have reached home');
    } else {
    resolve("You haven't reached home");
    }
  })
}

function makeRequest(response) {
    return new Promise((resolve,reject)=>{
    console.log(response);
    resolve(`Current location:- ${response}`);
  })
}

newRequest('home').then(response =>{
return makeRequest(response);
}).then(makeResponse => console.log(makeResponse)).catch((err) => console.log(err));

//Output
//"You have reached home"
//"Current location:- You have reached home"
Enter fullscreen mode Exit fullscreen mode

In the above example, the newRequest function returns a promise that takes a parameter place based on which promise is resolved. The makeRequest function returns a promise which is always resolved. The two functions are executed in order the second promise waits for the first one.

The above code can be simplified by with the use of Async/Await

function newRequest(place) {
    return new Promise((resolve,reject)=>{
    if(place === 'home') {
    resolve('You have reached home');
    } else {
    resolve("You haven't reached home");
    }
  })
}

function makeRequest(response) {
    return new Promise((resolve,reject)=>{
    console.log(response);
    resolve(`Current location:- ${response}`);
  })
}

async function checkLocation() {
try {
const  response = await newRequest('home');
const  processed = await makeRequest(response);
console.log(processed);
} catch (err) {
console.log(err);
}
}

checkLocation();

//OUTPUT
// "You have reached home"
// "Current location:- You have reached home"

Enter fullscreen mode Exit fullscreen mode

In this example, checkLocation is declared using the async keyword. The async keyword tells javascript that the following function is asynchronous. The checkLocation works exactly the same as the promises returning the same output. As you can see it looks a lot better and readable than the first example.
Error handling is done with the help of a try-catch block.

Async Await is just like promises in a way makes it easier to write promises.

//A simple example
const delay = ms => new Promise(res => setTimeout(res, ms));

const yourFunction = async () => {
  await delay(5000);
  console.log("Waited 5s");

  await delay(5000);
  console.log("Waited an additional 5s");
};

yourFunction();
Enter fullscreen mode Exit fullscreen mode

Thank for your time

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

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