异步箭头函数的语法

Syntax for an async arrow function

我可以使用 async 关键字将 JavaScript 函数标记为“异步”(即返回承诺)。像这样:

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
})

class 中使用 async method:

async foo() {
  // do something
}

这是将 async 箭头函数 expression 分配给 named 变量的最简单方法:

const foo = async () => {
  // do something
}

(注意这并不严格等同于async function foo() { }。除了, the function in this answer is not "hoisted to the top"。)

你也可以这样做:

 YourAsyncFunctionName = async (value) => {

    /* Code goes here */

}

立即调用异步箭头函数:

(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;
  };

我的异步函数

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);
});
}
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');