02. Async Function Syntax
Async functions defined as a regular functions:
Async function has the keyword
async
before it.The
await
keyword can only be used inside functions defined withasync
.
async function functionDeclaration() {
/**/
}
const functionExpression = async function() {
/**/
};
const arrowFunction = async () => {
/**/
};
const object = {
async methodName() {
/**/
}
};
class C {
async methodName() {}
async ["computedName"]() {}
}
Вызов асинхронной функции выглядит так же как и вызов любой другой функции.
Return value
Any async function returns a promise implicitly, and the resolve value of the promise will be whatever you return from the function.
Обычный
return
возвращает Promise установленный в возвращаемое значение.Выброс ошибки возвращает Promise установленный в ошибку.
Нормальный случай:
async function resolveAsyncFunction() {
return 123;
}
resolveAsyncFunction().then(x => console.log(x)); // 123
Выброс исключения:
async function rejectAsyncFunction() {
throw new Error("Problem!");
}
rejectAsyncFunction().catch(err => console.log(err)); // Error: Problem!
Last updated
Was this helpful?