Introduction
The async keyword is used to declare an asynchronous function in JavaScript. An asynchronous function always returns a Promise, even if it directly returns a simple value.
The async keyword was introduced as part of the Async/Await feature to make asynchronous code easier to read and write. Instead of chaining multiple .then() methods, developers can write asynchronous code that looks and behaves much like synchronous code.
In Node.js, the async keyword is commonly used with file operations, API requests, database queries, browser automation, and other asynchronous tasks.
For automation engineers, the async keyword is used extensively in frameworks such as Playwright, Puppeteer, WebdriverIO, and many Node.js libraries to simplify automation scripts.
In this tutorial, you’ll learn what the async keyword is, how it works, and how to use it effectively.
What is the async Keyword?
The async keyword is placed before a function declaration or function expression.
It tells JavaScript that the function is asynchronous and automatically returns a Promise.
Why Use the async Keyword?
The async keyword helps developers:
-
Write cleaner asynchronous code.
-
Improve code readability.
-
Reduce Promise chaining.
-
Simplify asynchronous workflows.
-
Improve maintainability.
-
Work seamlessly with
await. -
Handle asynchronous operations more naturally.
Syntax
async function functionName() {
return value;
}
Example 1: Basic async Function
async function greet() {
return "Hello World";
}
greet()
.then(function (message) {
console.log(message);
});
Sample Output
Hello World
Example 2: Returning a Number
async function getNumber() {
return 100;
}
getNumber()
.then(function (number) {
console.log(number);
});
Sample Output
100
Example 3: Returning an Object
async function getUser() {
return {
name: "Rahul",
city: "Delhi"
};
}
getUser()
.then(function (user) {
console.log(user);
});
Sample Output
{ name: 'Rahul', city: 'Delhi' }
Example 4: Using async with a Promise
async function loadData() {
return Promise.resolve(
"Data loaded."
);
}
loadData()
.then(function (message) {
console.log(message);
});
Sample Output
Data loaded.
Example 5: Arrow Function with async
const calculate = async () => {
return 50 * 2;
};
calculate()
.then(function (result) {
console.log(result);
});
Sample Output
100
Automation Testing Examples
The async keyword is widely used in automation frameworks to simplify asynchronous operations.
Playwright Example
Simulate opening an application.
async function openApplication() {
return "Application opened.";
}
openApplication()
.then(function (message) {
console.log(message);
});
Sample Output
Application opened.
Selenium Example
Launch a browser.
async function launchBrowser() {
return "Browser launched.";
}
launchBrowser()
.then(function (message) {
console.log(message);
});
Sample Output
Browser launched.
Cypress Example
Visit a webpage.
async function visitPage() {
return "Page visited.";
}
visitPage()
.then(function (message) {
console.log(message);
});
Sample Output
Page visited.
API Testing Example
Retrieve an API response.
async function fetchApi() {
return "API response received.";
}
fetchApi()
.then(function (message) {
console.log(message);
});
Sample Output
API response received.
Data-Driven Testing Example
Load test data.
async function loadTestData() {
return "CSV file loaded.";
}
loadTestData()
.then(function (message) {
console.log(message);
});
Sample Output
CSV file loaded.
Common Uses of the async Keyword
The async keyword is commonly used for:
-
Reading files.
-
Writing files.
-
API requests.
-
Database queries.
-
Browser automation.
-
User authentication.
-
Processing JSON data.
-
Uploading files.
-
Data validation.
-
Workflow automation.
Common Mistakes
Forgetting That async Returns a Promise
Even if an async function returns a simple value, it is automatically wrapped in a Promise.
Using await Outside an async Function
The await keyword can only be used inside an async function (unless using top-level await in supported ES modules).
Mixing Callbacks with async
Prefer using async and await together instead of mixing callbacks and Promise chains.
Best Practices
-
Use
asyncfor asynchronous functions. -
Combine
asyncwithawaitfor better readability. -
Handle errors using
try...catch. -
Use meaningful function names.
-
Keep asynchronous functions focused on a single responsibility.
-
Avoid unnecessary Promise wrapping inside
asyncfunctions. -
Write clean and readable asynchronous code.
Conclusion
The async keyword simplifies asynchronous programming by automatically returning a Promise and allowing developers to write cleaner, more readable code. It forms the foundation of the Async/Await syntax, making asynchronous workflows much easier to understand compared to traditional Promise chaining.
For automation engineers, the async keyword is an essential part of modern JavaScript development. It is used extensively in browser automation, API testing, file handling, and database interactions. Mastering the async keyword is the first step toward effectively using await and writing professional Node.js automation scripts.
Frequently Asked Questions (FAQs)
What does the async keyword do?
It declares an asynchronous function that always returns a Promise.
Does an async function always return a Promise?
Yes. Even if you return a simple value, JavaScript automatically wraps it in a Promise.
Can I use await without async?
No. The await keyword can only be used inside an async function (except for supported top-level await in ES modules).
Why is the async keyword important?
It makes asynchronous code easier to read, write, and maintain.
Why is async widely used in automation testing?
Modern automation frameworks use asynchronous operations for browser interactions, API requests, file handling, and database operations. The async keyword simplifies these workflows.
Key Takeaways
-
The
asynckeyword creates an asynchronous function. -
Every
asyncfunction automatically returns a Promise. -
Returned values are wrapped in resolved Promises.
-
asyncworks seamlessly with theawaitkeyword. -
It improves the readability of asynchronous code.
-
It reduces the need for long Promise chains.
-
Modern Node.js applications heavily rely on
async. -
Automation frameworks extensively use
async. -
Use
try...catchfor error handling inasyncfunctions. -
Understanding the
asynckeyword is essential before learning theawaitkeyword.
