The async keyword before a function makes it asynchronous. Such a function always returns a Promise, even if it returns a regular value. The async keyword allows using the [await] keyword inside the function to wait for other asynchronous operations.
// Regular function
function normalFunc() {
return 'result';
}
// Asynchronous function
async function asyncFunc() {
return 'result';
}
// Difference in return value
console.log(normalFunc()); // 'result'
console.log(asyncFunc()); // Promise { 'result' }
// Usage with await
async function getData() {
const result = await asyncFunc();
console.log(result); // 'result'
}The [async] keyword is like a special label on a function that says: “This function works with asynchronous operations”. It’s like a notification on a mailbox — it tells the postman that there might be special letters inside requiring special delivery! 📬
The [async] keyword before a function:
// Asynchronous function with regular return
async function greet() {
return 'Hello!';
}
// Same as:
// function greet() {
// return Promise.resolve('Hello!');
// }
greet().then(message => console.log(message)); // 'Hello!'// Function simulating asynchronous operation
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// Asynchronous function with await
async function delayedGreeting() {
console.log('Starting...');
await delay(1000); // Wait 1 second
return 'Done!';
}
// Usage
delayedGreeting().then(result => console.log(result));async function withValue() {
return 'value';
}
async function withPromise() {
return Promise.resolve('value');
}
// Both functions return Promise
console.log(withValue()); // Promise { 'value' }
console.log(withPromise()); // Promise { 'value' }async function mightFail() {
throw new Error('Error!');
}
// Same as:
// function mightFail() {
// return Promise.reject(new Error('Error!'));
// }
mightFail().catch(error => console.log(error.message)); // 'Error!'// Working with network
async function fetchUserData(userId) {
// Simulating server request
const response = await fetch('/api/users/' + userId);
const userData = await response.json();
return userData;
}// Instead of .then() chains
// fetch('/api/data')
// .then(response => response.json())
// .then(data => processData(data))
// .then(result => console.log(result))
// .catch(error => console.log(error));
// Better to use async/await
async function handleData() {
try {
const response = await fetch('/api/data');
const data = await response.json();
const result = processData(data);
console.log(result);
} catch (error) {
console.log(error);
}
}// ❌ Error — await outside async function
// function bad() {
// const result = await somePromise(); // SyntaxError!
// }
// ✅ Correctly
async function good() {
const result = await somePromise(); // Works!
}// ❌ Error — error not handled
// async function risky() {
// const data = await fetch('/api/data');
// // If fetch fails, error will "fall" up
// }
// ✅ Correctly — error handling
async function safe() {
try {
const data = await fetch('/api/data');
} catch (error) {
console.log('Error:', error);
}
}The [async] keyword is a simple way to work with asynchronous code, making it more readable and understandable. This is a modern standard for writing asynchronous JavaScript! 💪
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪