Modern JS Talk async function
Source: Dev.to
Overview
An async function returns an Async Function object. By using the async and await keywords, asynchronous processing can be written more concisely than with raw Promises. The feature was standardized in ES2017.
Basic Usage
Add the async keyword before a function definition. If the function returns a non‑Promise value, it is automatically wrapped in a resolved Promise.
async function asyncFunc() {
return 'Amazing!';
}
asyncFunc().then(result => {
console.log(result); // "Amazing!"
});Returning Values with Parameters
You can return a value that incorporates arguments; it will still be wrapped in a Promise.
async function asyncFuncB(text) {
return 'Amazing!' + text;
}
asyncFuncB('Indeed!').then(result => {
console.log(result); // "Amazing!Indeed!"
});Returning Promises Directly
An async function may also return an explicit Promise.
async function asyncFuncC() {
return new Promise((resolve, reject) => {
resolve('Wonderful!');
});
}
asyncFuncC().then(result => {
console.log(result); // "Wonderful!"
});The same logic can be expressed more succinctly:
async function asyncFuncC() {
return Promise.resolve('Wonderful!');
}
asyncFuncC().then(result => {
console.log(result); // "Wonderful!"
});Using await
Inside an async function, the await operator pauses execution until the awaited Promise settles, allowing you to write code without explicit .then() chains.
async function awaitFunc() {
return 'Wonderful!';
}
async function asyncFuncD() {
const result = await awaitFunc();
console.log(result); // "Wonderful!"
}
asyncFuncD();