[英]Syntax for an async arrow function
我可以使用async
关键字将 JavaScript function 标记为“异步”(即返回承诺)。 像这样:
async function foo() {
// Do something
}
箭头函数的等效语法是什么?
异步箭头函数如下所示:
const foo = async () => {
// do something
}
对于传递给它的单个参数,异步箭头函数看起来像这样:
const foo = async evt => {
// do something with evt
}
对于传递给它的多个参数,异步箭头函数看起来像这样:
const foo = async (evt, callback) => {
// do something with evt
// return response with callback
}
匿名表单也可以:
const foo = async function() {
// do something
}
异步函数声明如下所示:
async function foo() {
// do something
}
在回调中使用异步函数:
const foo = event.onCall(async () => {
// do something
})
在类中使用异步方法:
async foo() {
// do something
}
这是将async
箭头函数表达式分配给命名变量的最简单方法:
const foo = async () => {
// do something
}
(请注意,这并不严格等同于async function foo() { }
。除了function
关键字和箭头表达式之间的区别之外,此答案中的函数不是“提升到顶部” 。)
立即调用异步箭头函数:
(async () => {
console.log(await asyncFunction());
})();
立即调用异步函数表达式:
(async function () {
console.log(await asyncFunction());
})();
带参数的异步箭头函数语法
const myFunction = async (a, b, c) => {
// Code here
}
基本示例
folder = async () => {
let fold = await getFold();
//await localStorage.save('folder');
return fold;
};
async function foo() {
// do something
}
相当于:
const foo = async () => {
// do something
}
使用一个参数调用 foo,如下例所示:
async function foo(arg1) {
// do something
}
等效于像这样调用 foo (两种方式都可以接受,因为括号是可选的,但在仅提供一个参数时不是必需的)
const foo = async arg1 => {
// do something
}
const foo = async (arg1) => {
// do something
}
如果您使用两个或更多参数调用 foo
async function foo(arg1, arg2) {
// do something
}
相当于:(现在需要括号)
const foo = async (arg1, arg2) => {
// do something
}
对于内部使用 await 的实际示例:
const foo = async () => await Promise.resolve('done');
你也可以这样做:
YourAsyncFunctionName = async (value) => {
/* Code goes here */
}
我的异步功能
const getAllRedis = async (key) => {
let obj = [];
await client.hgetall(key, (err, object) => {
console.log(object);
_.map(object, (ob)=>{
obj.push(JSON.parse(ob));
})
return obj;
// res.send(obj);
});
}
最简单的方法
const MyFunction = async ()=>{
// do something here
}
对于静态异步箭头函数,它的工作原理如下:
static myFunction = async () => {
// your code here
}
const asynchronousFunction = async () => {
// do something;
// await something else;
}
/ * foo =异步(props)=> {
/* Code goes here */
},请删除这些评论* /
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.