異步箭頭功能的語法

本文翻譯自: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
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章