本文翻译自:Syntax for async arrow function
I can mark a javascript function as "async" (ie returning a promise) with the async
keyword. 我可以使用async
关键字将javascript函数标记为“异步”(即返回承诺)。 Like this: 像这样:
async function foo() {
// do something
}
What is the equivalent syntax for arrow functions? 箭头功能的等效语法是什么?
#1楼
参考:https://stackoom.com/question/2uGvO/异步箭头功能的语法
#2楼
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
})
#3楼
This the simplest way to assign an async
arrow function expression to a named variable: 这是将async
箭头函数表达式分配给命名变量的最简单方法:
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() { }
。除了function
关键字和箭头表达式之间的区别之外,此答案中的函数没有“提升到顶部” 。)
#4楼
You may also do: 您也可以这样做:
YourAsyncFunctionName = async (value) => {
/* Code goes here */
}
#5楼
Immediately Invoked Async Arrow Function: 立即调用异步箭头功能:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression: 立即调用异步函数表达式:
(async function () {
console.log(await asyncFunction());
})();
#6楼
Async Arrow function syntax with parameters 带参数的异步箭头函数语法
const myFunction = async (a, b, c) => {
// Code here
}