Free Web Development Online Tutorials, Learn to Code
how to write javaScript async function, async await javascript example

Asynchronous JavaScript Tutorial

What is Asynchronous Call?

Normally JavaScript is single-threaded programming language, which means it can perform only one thing at a time, when some JavaScript function executed, it has to complete before we can execute another JavaScript function , also UI will be blocked during any JavaScript call.

Now, in new version of JavaScript (ES6) we can write asynchronous JavaScript function, that means before one function gets completed we can execute another JavaScript function, it does not block the UI anymore, and JavaScript is now multi threaded programming language.

You may need Visual Studio Code or something similar editor.

Async JavaScript Examples

To write an async function in JavaScript, you just need to place async keyword before function keyword.

async function welcomeMessage() {
    console.log("Hello World");
  }

You also can explicitly write a promise inside an async function like example below.

async function welcomeMessage() {
            return Promise.resolve("Hello, how are you!");
  }

Remember that Await works only inside a async function.

    let result = await promise;

Here is very simple example of async JavaScript function.

let checkUser = async function(username, password){
try {
let result = setTimeout(() => console.log("Tick"), 500);
    console.log("Welcome "+ username);
    return result;
    }
    catch (ex)
    {
        console.log(ex)
    }
 };

 console.log(checkUser("u1","p1"));

Notice, "async" in above function gets converted into a new "Promise".

Now look at below example how you can use "await" in "async" function.

let checkUser = async function(username, password){
try {
let result=await updateLog();
console.log("Welcome "+ username);
return result;
}
catch (ex)
{
console.log(ex);
}
};
function updateLog() {
return new Promise(resolve => {
setTimeout(() => {
        resolve("resolving okay");
      }, 2000);
    });
  }

 console.log(checkUser("u1","p1"));
Comment
Name
Email
Website
Subscribe