I can mark a JavaScript function as "async" (i.e., returning a promise) with the async
keyword. Like this:
async function foo() {
// Do something
}
What is the equivalent syntax for arrow functions?
Async arrow functions look like this:
const foo = async () => {
// do something
}
Async arrow functions look like this for a single argument passed to it:
const foo = async evt => {
// do something with evt
}
Async arrow functions look like this for multiple arguments passed to it:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymous form works as well:
const foo = async function() {
// do something
}
An async function declaration looks like this:
async function foo() {
// do something
}
Using async function in a callback:
const foo = event.onCall(async () => {
// do something
})
Using async method inside of a class:
async foo() {
// do something
}
This the simplest way to assign an async
arrow function expression to a named variable:
const foo = async () => {
// do something
}
(Note that this is not strictly equivalent to async function foo() { }
. Besides the differences between the function
keyword and an arrow expression, the function in this answer is not "hoisted to the top".)
async function foo() {
// do something
}
Is equivalent to:
const foo = async () => {
// do something
}
if you call foo with one argument like the following example:
async function foo(arg1) {
// do something
}
Is equivalent to:
const foo = async arg1 => {
// do something
}
if you call foo with two arguments or more like the following example:
async function foo(arg1, arg2) {
// do something
}
Is equivalent to:
const foo = async (arg1, arg2) => {
// do something
}
And for a practical example with an await use inside:
const foo = async () => await Promise.resolve('done');
var foo = async () => await Promise.resolve('ha');
- works just fine – Jaromanda Xit doesn't work
is meaningless ... are you getting an error? perhaps you're doing something else wrong, without the code that "doesn't work" and a meaningful description of how it doesn't work, can only guess that you're doing something wrong (or using an old browser) – Jaromanda X