async and await are keywords in JavaScript used in handling asynchronous operations. They were introduced in ECMAScript 2017 to work with promises more comfortably, allowing for better syntax and logic flow when dealing with asynchronous code, like API requests, file reading, etc.
async
The async function returns a promise and allows you to use await within it. Any return value from an async function is automatically wrapped in a Promise.resolve().
Visual Representation
Example
async function mando() {
return 'baby yoda';
}
mando().then(data => {
console.log(data) // This will log 'baby yoda'
})
/* same as above
function mando() {
return Promise.resolve('baby yoda');
}
mando().then(value => {
console.log(value); // This will log 'baby yoda'
});*/
Output
baby yoda
await
The await keyword is used inside an async function to pause the execution of the function until a promise is resolved (or rejected).
Example
async function mando() {
let promise = new Promise((resolve, reject) => {
// Simulating a delay of 2 seconds using setTimeout
setTimeout(() => resolve("Baby Yoda"), 2000)
});
// The execution of mando() pauses here until the promise resolves
let result = await promise;
console.log(result);// Logs the result after 2 seconds
}
mando(); // Call the function
Output
The mando() function returns the Promise, and the await keyword makes wait for 2 seconds, and after that, it will return the value “Baby Yoda”.
The function execution “pauses” because of setTimeOut() and resumes when the Promise settles, with the result becoming its result. So the code above shows “Baby Yoda” in 2 seconds.
Browser Compatibility
- Chrome 55 and above
- Firefox 52 and above
- Safari 10.1 and above
- Opera 42 and above
- Edge 14 and above
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.