Beginner's guide to Javascript's Async/Await

Beginner's guide to Javascript's Async/Await

·

6 min read

Have you ever felt like 'What the heck is Async/Await in javascript'. Many people who are new to javascript are being confused of Async , Await , promises. In this article I want to make it easy for you. By the end , you would be able to have a general knowledge on what Async/Await are and how they are used!

To understand Async you need to know about Promises in javascipt before.

Promises

Promises in javascript are just like in real world promises. If you promise someone then you may stick to the promise or you may not. That's the same case in javascript. Let us look at the example below.

 function validate(username){
    let promise=new Promise((resolve,reject)=> {
        if(username=="john"){
            resolve("yay success user is john ");
        }
        else{
            reject("unknown user!");
        }
    });
    return promise;
}

validate("john").then(msg=>{
    console.log(msg);
}).catch(err=>{
    console.log(err);
});
//output -  yay success user is john

The function validate returns a promise.The function passed to the new Promise is known as executer. When new Promise is created the executer runs automatically. resolve and reject are callbacks. resolve - when the job is executed succesfully. reject -if an error occured.then and catch are consumers. .then is a function that runs when a promise is resolved. .catch is a function that runs when promise is rejected.

Async and Await

okay, you have now got a basic idea on what promises are. Now lets get to Async and Await. Let us understand what problems are we facing with javascript without Async and Await. Look at the code below and try to analyze it.

const one=()=>{
    return "this is one";
}
const two= ()=>{
    //returns after 3 sec
    setTimeout(()=>{
        return "this is two!"; 
    },3000);
}

const three=()=>{
    return "this is three!";
}

function callAll(){
    let valOne=one();
    console.log(valOne);

    //will be undefined since it return after 3 sec and console.log()
    //  doesnot wait for that much long
    //so we use async and await
    let valTwo=two();
    console.log(valTwo);


    let valThree=three();
    console.log(valThree);
}

callAll();

/*output -
        this is one 
        undefined
        this is three!   */

Might be wondering where this undefined has come from right?. Actually the two() function returns the value after 3 sec.But console.log(valTwo) did not wait until it's executed. So it logs the value undefined to the console.

How to get rid of this problem?

Now we use async and await to solve the above problem. Look at the code below.

const one=()=>{
    return "this is one";
}
const two= ()=>{
    //returns after 3 sec
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve("this is two");
        },3000);
    })
}

const three=()=>{
    return "this is three!";
}


async function callAll(){
    let valOne=one();
    console.log(valOne);


    let valTwo= await two();
    console.log(valTwo);


    let valThree=three();
    console.log(valThree);
}


callAll();

/* output -
        this is one
        this is two           - logs after 3 sec
        this is three!  */

we declared the function callAll() with async keyword.async functions enable us to write promise based code as if it were synchronous. The keyword await makes javascript wait until the function returns promise. The remaining code runs only after the promise is returned.

NOTE - await only works in async functions

Let me make it more clear to you by considering other example.

function test(){
    return new Promise((resolve,reject)=>{
        setTimeout(()=>{
            resolve("Promise is resolved");
        })
    },3000);
}


async function first(){
    console.log("before promise");
    let valTwo= await test();
    console.log(valTwo);

    console.log("After promise")

}

function second(){
        console.log("in function second");

}

first();
second();

/* output - 
     before promise
     in function second 
     Promise is resolved
      After promise  
*/

When ever you go through await keyword in an async function , javascript leaves the function and executes the remaining part of the code. Whenever the promise is returned then it continues to execute the remaining part of the previous function. As you can see that the second() function gets executed while the first is being executing.

Hope you have learnt something from this article. Still if you aren't clear about the async/await .Please let me know in the comments section!

Let's connect on Twitter