In JavaScript, the async
keyword is used to define a function that always returns a Promise and allows the use of await
within its body to pause execution until a Promise settles.
async
DoesPlacing async
before a function declaration ensures that the function returns a Promise, even if it appears to return a plain value
Example:
javascriptasync function myFn() { return "Hello"; } *// Equivalent to:* function myFn() { return Promise.resolve("Hello"); }
The actual return value is always wrapped in a resolved Promise, unless an error is thrown, in which case the Promise is rejected
await
Inside async
FunctionsThe await
keyword can only be used inside an async function
await
pauses the function execution until the awaited Promise resolves, then resumes execution and returns the resolved value.
Example:
javascriptasync function fetchData() { const response = await fetch("<https://jsonplaceholder.typicode.com/posts/1>"); const data = await response.json(); console.log(data); } fetchData();
This way, asynchronous code reads more like synchronous code, making it easier to understand and maintain.
.then
or caught with .catch
(or via try..catch
inside the function).async/await
enables various asynchronous control flows:
Promise.all
and await
.Async functions and the await
keyword are fundamental for modern JavaScript development, especially when handling I/O, APIs, and other asynchronous tasks.
Async functions in JavaScript differ from regular functions mainly in their return value and their ability to pause execution to wait for asynchronous operations using await