Javascript Async/Await function

Pasan Kamburugamuwa
2 min readJan 9, 2023

--

In this short article, I will explain what is Javascript async/await function as with going forward, need to have good knowledge of how Javascript behaves in some occasions of events.

The asynchronous behavior of the Javascript enables to run your program while running the other events of the application. This will help to maintain the responsiveness of the web page. So before going deep dive in to what is asynchronous programming, let’s have a discussion about what is synchronous programming.

Synchronous Programming

In the synchronous programming, the Javascript code is executed line by line. At each line, the browser waits for the line to finish its work before going to the next line.

Example

const name = 'Asynchronous';
const welcome = `Hello, ${name} functions!`;
console.log(welcome);

Let’s have a look at how the code executed with functions.

function welcome(name) {
return `Hello, ${name} functions!`;
}

const name = 'Asynchronous';
const welcomeVar = welcome(name);
console.log(welcomeVar);

Still the program runs with in synchronously. Because the caller has to wait for the function to finish its work and return a value before the caller can continue.

Asynchronous Programming

This is a technique which is used to start a potentially long running task and still be able to be responsive to other events while that task is running. Once that task is finished, the program can represented the results.

Below is an example which explain how the things going with the asynchronous programming. Imagine the baseURI contains something which getting much larger json data and it might take couple of seconds to retrieve it. So with using the asynchronous functions, this will be running with other events of the program and lead to work cooperately.

Example

fetchUsers: async function(){
const baseURI = 'https://jsonplaceholder.typicode.com/users'
await this.$http.get(baseURI)
.then((result) =>{
this.users = result;
})
},

As from the above examples, we might be able to come to a conclusion that the asynchronous functions are used in where the execution is blocked indefinitely. Some of the examples of this are network requests, long-running calculations, file systems operations like that. Using asynchronous code in the browser allows to remain the other functions work and also the keep the user experience unaffected.

Thanks and see you in the next tutorial.

--

--