async function
Declares a function that always returns a promise and may use await.
Syntax
async function name(params) {
// ... may use await ...
}
Returns
Promise — Calling an async function returns a promise that resolves with the
function's return value or rejects with a thrown error.
Examples
async function getValue() {
return 42;
}
getValue().then(v => console.log(v));
Output
42
function delay(ms, v) {
return new Promise(r => setTimeout(() => r(v), ms));
}
async function main() {
const x = await delay(0, "done");
console.log(x);
}
main();
Output
done
async function fail() {
throw new Error("oops");
}
fail().catch(e => console.log(e.message));
Output
oops
Notes
- `await` may only be used inside an async function (or at the top level
of a module).
- A non-promise return value is wrapped in a resolved promise.
- Use `try...catch` around `await` to handle rejections.
Browser & runtime support
| Environment | Since version |
|---|---|
| chrome | 55 |
| firefox | 52 |
| safari | 11 |
| edge | 15 |
| node | 7.6 |