问题
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?
回答1:
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
}
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
})
回答2:
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".)
回答3:
Immediately Invoked Async Arrow Function:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression:
(async function () {
console.log(await asyncFunction());
})();
回答4:
You may also do:
YourAsyncFunctionName = async (value) => {
/* Code goes here */
}
回答5:
Async Arrow function syntax with parameters
const myFunction = async (a, b, c) => {
// Code here
}
回答6:
/*foo = async (props) => {
/* Code goes here */
} Please remove these comments*/
来源:https://stackoverflow.com/questions/42964102/syntax-for-async-arrow-function