Writing cleaner asynchronous code with async/await

Writing cleaner asynchronous code with async/await

In JavaScript programming, async and await contribute to the maintainability and readability of asynchronous program code instead of callback methods or promise functions. They help JavaScript programmers to create asynchronous program source code in a proper asynchronous order, so that the program source code looks and behaves like synchronous code, which allows programmers to pass and avoid task arguments in callback hell or deeply nested .then() chains in the program.

Writing cleaner asynchronous code with asyncawait

async and await functions in JavaScript.

  • async function – A function declared with async function in JavaScript program, and it automatically returns a promise value to the program. In JavaScript program async keyword is used to define a function that always returns a promise value to the current program, whether the program returns a promise value or generates an error as output.
  • await function – Inside an async function in a JavaScript program, the await keyword can be used to stop the execution of the function until the promise condition argument is resolved or rejected in the current program. This function enables the synchronous behaviour of the asynchronous program source code in the current program.

Basic syntax of async function in JavaScript.

/async function testAsyncFunction()

return “Welcome to Vcanhelpsu Website”;

}

// here it use to Calling the test async function

testAsyncFunction().then(output => console.log(output)); // it display output – Welcome to Vcanhelpsu Website

Here in this program testAsyncFunction function is an asynchronous function, and this function automatically returns a promise value in order.

In this condition, testAsyncFunction returns the text message “Welcome to Vcanhelpsu Website”.

Use of await function in JavaScript.

Await keyword is applied in JavaScript program to follow the wait process for the resolution of a program promise task. This function can be applied only inside async function. When a promise in the current program is resolved and returns a value, here await function returns the resolved output value. Here if the promise condition is rejected in the program, it will generate an error in the current program, then programmers can catch it in the current program by applying try-catch block.

Example of async and await in JavaScript.

// let create an asynchronous process using a promise function

function process1() {

return new Promise((resolve, reject) => {

setTimeout(() => {

resolve(“process 1 is done”);

}, 2000);

});

}

// here we use async/await function to control

async function executeprocess() {

const output = await process1(); // here it Wait for process1 to resolve

console.log(output); // it display the result “process 1 is done”

}

executeprocess();

Explanation of async and await function.

In this program process1() returns a promise value which is automatically resolved after 2 milliseconds.

Here inside executeprocess(), we apply await function to wait for process1() to resolve before logging the output message.

The executeprocess() function is an asynchronous function.

Handling multiple asynchronous operations in a JavaScript program.

When handling multiple asynchronous function operations in a JavaScript program, programmers can apply the await function for each program operation. The program source code will execute in sequential order, here the program will wait until each promise is resolved before moving to the next line.

Example of multiple asynchronous sequential execution.

function process2() {

return new Promise((resolve, reject) => {

setTimeout(() => {

resolve(“Process 2 is done”);

}, 2000);

});

async function executeprocess() {

const output1 = await process1(); // here it Wait for process1 to solve

console.log(output1); // its display result “Process 1 is done”

const output2 = await process2(); // here it Wait for process2 to solve

console.log(output2); // here it display the result “Process 2 is done”

}

executeprocess();

Explanation of multiple asynchronous sequential.

Here in this program firstly, process1() is waited for completion and result is displayed in the output.

After this, process2() task is waited for and its result is displayed in the output.

Multiple tasks are executed in sequential order, means second process task will not start until first process task is completed.

Parallel execution with async/await in JavaScript.

If JavaScript programmer needs to execute multiple asynchronous tasks in parallel order in sequence, JavaScript programmer can apply Promise.all() function along with async/await function to execute all task process promises simultaneously rather than waiting for each task process to complete execution in one-by-one order manually.

Example of JavaScript parallel execution.

async function executeprocessInParallel() {

const [output1, output2] = await Promise.all([process1(), process2()]);

console.log(output1); // it display the output “process 1 is done”

console.log(output2); // it display the output “process 2 is done”

}

executeprocessInParallel();

Explanation of JavaScript parallel execution

In this program, Promise.all() inputs an array of promises, and waits for all these promise processes to resolve.

Here the output results of both process1() and process2() are returned as an array, which is displayed in output1 and output2.

Here by applying the Promise.all() function, we execute both the task processes simultaneously, and both the task processes terminate automatically once the last task completes.

Use of async/await function in Promise.all() for concurrent execution and error management in JavaScript.

If JavaScript programmers apply the Promise.all() function for parallel task execution, and want to manage the errors generated in the program, then programmers can use the try-catch block method to each individual promise method, or apply a .catch() block to each individual promise inside the Promise.all() function. Whereas, if programmers need a single promise rejection management, then the entire Promise.all() function in the program will fail or reject.

Example of error handling with async/await function with Promise.all().

async function executemultipleprocess() {

try {

const [output1, output2, output3] = await Promise.all([

process1(), // process1 done successfully

process2(), // process2 done successfully

process3() // here it Rejects process3 with an program error

]);

console.log(output1);

console.log(output2);

console.log(output3);

} catch (error) {

console.log(“it display Error”, error); // here it used to catch the error from process3

}

}

executemultipleprocess();

Here in this condition, process3 task fails, due to this, the complete Promise.all() function is rejected, and the error in the program is caught in the catch block.

Benefits of using async/await in JavaScript programming.

  • Program readability – The async/await function in JavaScript programs enables asynchronous source code to preview and behave like synchronous code, making these programs easier to read, write and understand.
  • Source code error management – Program error management with try-catch block in JavaScript is easier than dealing with .catch() block in promise chain.
  • Easy maintenance – async/await function reduces the complexity of callback methods in the existing program, and makes the asynchronous flow of the program clearer and more maintenance compatible.
  • Code error propagation – JavaScript programmers can easily manage and explore errors in asynchronous program code by applying the throw keyword just like in synchronous program source code.

Summary of async and await function methods in JavaScript.

  • Async functions in JavaScript programs always return a promise method value.
  • Whereas await function stops the default execution of an async function in the program until a promise in the current program is completed or rejected, thereby converting asynchronous source code to be more readable and synchronous.
  • If needed, programmers can apply the try-catch block method for source code error management in async/await functions.
  • If needed, the programmer can apply the Promise.all() function to run the program promises in parallel order and wait for all the promises to resolve.
  • The async/await function in JavaScript programming helps the programmer to create clearer, more maintenance compatible, and more readable asynchronous program source code in JavaScript.

Leave a Reply