Javascript 异步箭头函数的语法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42964102/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Syntax for async arrow function
提问by BonsaiOak
I can mark a javascript function as "async" (i.e. returning a promise) with the asynckeyword. Like this:
我可以使用async关键字将 javascript 函数标记为“异步”(即返回承诺)。像这样:
async function foo() {
// do something
}
What is the equivalent syntax for arrow functions?
箭头函数的等效语法是什么?
回答by BonsaiOak
Async arrow functionslook like this:
异步箭头函数如下所示:
const foo = async () => {
// do something
}
Async arrow functionslook like this for a single argumentpassed to it:
对于传递给它的单个参数,异步箭头函数看起来像这样:
const foo = async evt => {
// do something with evt
}
Async arrow functionslook like this for multiple argumentspassed to it:
对于传递给它的多个参数,异步箭头函数看起来像这样:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
The anonymousform works as well:
该匿名形式的作品,以及:
const foo = async function() {
// do something
}
An async function declarationlooks like this:
异步函数声明如下所示:
async function foo() {
// do something
}
Using async function in a callback:
在回调中使用异步函数:
const foo = event.onCall(async () => {
// do something
})
回答by Edoardo L'Astorina
This the simplest way to assign an asyncarrow function expressionto a namedvariable:
分配一个简单的方法async箭头函数表达式的命名变量:
const foo = async () => {
// do something
}
(Note that this is not strictly equivalent to async function foo() { }. Besides the differences between the functionkeyword and an arrow expression, the function in this answer is not "hoisted to the top".)
(请注意,这并不严格等同于async function foo() { }。除了关键字和箭头表达式之间的差异function之外,此答案中的函数并未“提升到顶部”。)
回答by Michael
Immediately Invoked Async Arrow Function:
立即调用异步箭头函数:
(async () => {
console.log(await asyncFunction());
})();
Immediately Invoked Async Function Expression:
立即调用异步函数表达式:
(async function () {
console.log(await asyncFunction());
})();
回答by codemirror
Async Arrow function syntax with parameters
带参数的异步箭头函数语法
const myFunction = async (a, b, c) => {
// Code here
}
回答by Chaurasia
Basic Example
基本示例
folder = async () => {
let fold = await getFold();
//await localStorage.save('folder');
return fold;
};
回答by Justin E. Samuels
You may also do:
你也可以这样做:
YourAsyncFunctionName = async (value) => {
/* Code goes here */
}

