async function
Declares an asynchronous function that always returns a promise and can use the await keyword inside it.
- Returns
- A promise (
Promise) that fulfills with the value fromreturn, or is rejected with the thrown error.
Example
#const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
async function loadProfile(name) {
await wait(300)
return { name, level: 7 }
}
const promise = loadProfile('Emma')
console.log(promise)
const profile = await promise
console.log(profile)Definition and usage
#The async keyword before a function turns it into an asynchronous function. Such a function always returns a promise: the value from return becomes the value of the fulfilled promise, and a thrown exception causes it to be rejected.
Inside an async function you can use await to wait for another promise’s result. The code then looks like ordinary, top-to-bottom code, and you catch errors with the familiar try...catch block instead of the catch() method.
async works with every form of function: a declaration, an expression, an arrow function (async () => {}), and a method on an object or class. Calling an async function doesn’t block the program. Code written after the call runs immediately, before the function finishes its work.
Syntax
#async function name(param1, param2) {
…
}
const name = async (param) => {
…
}More examples
#async function buyCourse(price, balance) {
if (balance < price) throw new Error('Not enough coins')
return balance - price
}
buyCourse(50, 80).then((rest) => console.log('Left:', rest))
buyCourse(90, 80).catch((error) => console.log('Error:', error.message))const getPoints = async () => 120
const shop = {
async buy(item) {
const points = await getPoints()
return `${item}: ${points - 100} points left`
}
}
console.log(await shop.buy('New avatar'))Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- Simply calling an
asyncfunction gives you aPromiseobject. To get the result, useawaitorthen(). - Don’t mark a function as
asyncif it doesn’t do anything asynchronous. You’d needlessly turn its result into a promise. - Handle an
asyncfunction’s errors withtry...catchinside it, or withcatch()at the call site.
Related entries
#- async/await vs then()async/await lets you write asynchronous code like ordinary, sequential code, with errors in try...catch, while then() builds a chain of calls on the promise itself.
- awaitPauses an async function until a promise settles, then returns its value or throws its error.
- PromiseAn object representing the result of an operation that will be available in the future: a value on success or an error.
- try...catchCatches errors thrown in the try block and handles them in catch. The optional finally always runs.
- functionDeclares a named function: a block of code with parameters that you can call any number of times and that can return a result.
- () => {}An arrow function: a shorter function syntax, with no own this, and an implicit return for a single expression.
- fetch()Sends an HTTP request and returns a promise with the server’s response (a Response object).
Spotted a mistake or missing an example? Write to us.