907

I can mark a JavaScript function as "async" (i.e., returning a promise) with the async keyword. Like this:

async function foo() {
  // Do something
}

What is the equivalent syntax for arrow functions?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
BonsaiOak
  • 27,741
  • 7
  • 30
  • 54
  • 2
    It's worth noting that at least firefox and babel does let you do that – Jaromanda X Mar 22 '17 at 22:55
  • 41
    `var foo = async () => await Promise.resolve('ha');` - works just fine – Jaromanda X Mar 22 '17 at 22:56
  • 2
    saying `it doesn't work` is meaningless ... are you getting an error? perhaps you're doing something else wrong, without the code that "doesn't work" and a meaningful description of how it doesn't work, can only guess that you're doing something wrong (or using an old browser) – Jaromanda X Mar 22 '17 at 22:57
  • @JaromandaX well I can't find it in any spec, so far at least – Pointy Mar 22 '17 at 22:58
  • 1
    that may well be @Pointy, but it does work natively in current firefox and chrome and node.js (7.7.4) – Jaromanda X Mar 22 '17 at 22:59
  • 1
    The [ES2017 spec](https://tc39.github.io/ecma262/#sec-async-arrow-function-definitions) has a section on async arrow function definitions @Pointy. – Heretic Monkey Mar 22 '17 at 23:05
  • @MikeMcCaughan yes I'm just getting to that; I figured it had to be somewhere because I saw some Babel discussions about it (thanks) – Pointy Mar 22 '17 at 23:08
  • What do you mean by "*equivalent syntax for Node.js*"? As soon as node supports `async`/`await`, it will support exactly that syntax. – Bergi Mar 22 '17 at 23:10
  • It turned my problem was actually that I hadn't updated node.js to the latest version. I would have seen that immediately but I couldn't find a good example of correct syntax. I've updated my question to reflect that. – BonsaiOak Mar 22 '17 at 23:10
  • 1
    @JaromandaX You're right. I should have posted my error message. – BonsaiOak Mar 22 '17 at 23:11
  • @Bergi I edited in a hurry and made the silly mistake of writing "node.js" instead of "arrow functions" See my updated question. – BonsaiOak Mar 22 '17 at 23:12
  • @BonsaiOak - you still can, it's not too late – Jaromanda X Mar 22 '17 at 23:14

11 Answers11

1560

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
}

Async arrow functions look like this for multiple arguments passed to it:

const foo = async (evt, callback) => {
  // do something with evt
  // return response with callback
}

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

Using async method inside of a class:

async foo() {
  // do something
}
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
BonsaiOak
  • 27,741
  • 7
  • 30
  • 54
  • 20
    The OP appears to be looking for a named, async, arrow function which is the one syntax you do not show. – jfriend00 Mar 22 '17 at 23:19
  • 67
    Actually, `const foo = async () => {}` creates a named async function named `foo`. It's entirely possible to do named functions this way (just no hoisting). In ES2016+ assignment of an anonymous function to a variable names it after the variable if it is declared there. – Benjamin Gruenbaum Mar 22 '17 at 23:55
  • @BenjaminGruenbaum What changed in es2016+? I thought it was always that way. – BonsaiOak Mar 23 '17 at 18:46
  • 9
    @BenjaminGruenbaum Please don't call it named function. In js, a named anonymous function is a very specific syntax `foo = function bar () {}` that was created to replace `arguments.callee` when writing recursive anonymous functions. What you have there is a variable named `foo` that is a reference to a function. – slebetman Jun 04 '17 at 02:32
  • 27
    @slebetman since ES2015 when you do `const foo = async () => {}` the name of the function is set to `foo` - http://www.ecma-international.org/ecma-262/6.0/#sec-assignment-operators-runtime-semantics-evaluation and http://www.ecma-international.org/ecma-262/6.0/#sec-object-initializer-runtime-semantics-propertydefinitionevaluation - see discussion in https://esdiscuss.org/topic/name-anonymous-functions-on-property-assignments – Benjamin Gruenbaum Jun 04 '17 at 19:03
  • What is the difference if we use async function with constanta. const somefunction = async () => {} – Faris Rayhan Feb 02 '18 at 11:09
  • 2
    @FarisRayhan It's just as with other constants, the reference of the variable `somefunction` cannot be changed after it is set. (It points to your anonymous async function.) – Qwerty Jul 24 '18 at 12:16
  • If calling from another `async` function, you can also wait for anonymous/arrow functions using `await (async () => { // do something });` – Jérôme Beau Oct 18 '18 at 15:42
  • I have defined my function like this: getDataFromPhoneNumber = (phone) => { return new Promise((resolve, reject) =>{ /*stuff here*/ } } how do I make that async ? – MLissCetrus Jan 29 '20 at 22:40
  • @MLissCetrus just like the answer suggests: `async phone => {/* stuff here */}` – Falco Jun 12 '20 at 13:55
  • 1
    @BenjaminGruenbaum: `const foo = async () => …` sets the `.name` property on the function (just like `var foo = function () {…` did in ES5—this is only a change in that `const` an arrow functions did not exist in ES5— but that doesn't make the function a *named* function. Consider: in the `var foo` case you can change the value of `foo` and whoops, function can no longer call itself. That's different than `function foo() {…`, where `foo` can always call itself by that name. – cpcallen Oct 09 '20 at 11:02
150

This the simplest way to assign an async arrow function expression to a named variable:

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".)

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
Edoardo L'Astorina
  • 7,235
  • 2
  • 12
  • 9
  • 11
    Note that a named function expression is a very specific syntax in javascript. This is NOT a named function expression. Using the right words is important to avoid confusion later on when one phrase can evolve to mean two things. FYI, a named function expression is: `foo = function myName () {}`. The name is `myName` and it is specified to only exist inside the anonymous function and not defined anywhere outside. It's purpose is to replace `arguments.callee` when writing recursive anonymous functions. – slebetman Jun 04 '17 at 02:30
  • 2
    I was about to dispute you @slebetman on technicality, since this is a (arrow) function expression and you end up with a named function (ie `foo.name === 'foo'`). But only because it's in the initializer of a `const` *statement*—meaning it's not quite right to call this a "named async arrow function expression". You're also correct that a named function expression's name is only _bound_ inside its own body, but it is also stored in the function's `name` property, which is nice for debugging (and is more often the reason I'd name them). – Vaz Sep 02 '17 at 23:32
  • 5
    To put it another way, there's no such thing as a "named arrow function expression", but it can become "named" by being part of a const or let _statement_ (not sure about var because of hoisting), in the sense of having a name `fn.name` as well as having a binding in scope (the variable). – Vaz Sep 02 '17 at 23:35
101

Immediately Invoked Async Arrow Function:

(async () => {
    console.log(await asyncFunction());
})();

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();
Marvin Fischer
  • 2,552
  • 3
  • 23
  • 34
Mihail
  • 1,246
  • 1
  • 9
  • 8
23
async function foo() {
  // do something
}

Is equivalent to:

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

Calling foo with one argument like in the following example:

async function foo(arg1) {
  // do something
}

Is equivalent to calling foo like this (both ways are acceptable since parentheses are optional but not required when just one argument is provided)

const foo = async arg1 => {
  // do something
}

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

if you call foo with two or more arguments

async function foo(arg1, arg2) {
  // do something
}

Is equivalent to: (parentheses are now required)

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

And for a practical example with an await use inside:

const foo = async () => await Promise.resolve('done');
Ran Turner
  • 14,906
  • 5
  • 47
  • 53
22

Async Arrow function syntax with parameters

const myFunction = async (a, b, c) => {
   // Code here
}
Stephen M Irving
  • 1,324
  • 9
  • 20
codemirror
  • 3,164
  • 29
  • 42
21

Basic Example

folder = async () => {
    let fold = await getFold();
    //await localStorage.save('folder');
    return fold;
  };
Chaurasia
  • 494
  • 1
  • 6
  • 22
15

You may also do:

 YourAsyncFunctionName = async (value) => {

    /* Code goes here */

}
Justin E. Samuels
  • 867
  • 10
  • 28
  • 6
    with one param you don't need parenthesis. YourAsyncFunctionName = async value => { /* Code goes here */ } – Zsolt Takács Mar 18 '18 at 19:48
  • 3
    @TakácsZsolt it a matter of preference. What Justin did is not wrong. I like to put parenthesis just in case I have add more params in the future – Patricio Vargas Sep 03 '20 at 04:58
7

My async function

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);
});
}
suraj gholap
  • 347
  • 4
  • 3
  • 2
    Please edit your answer to explain how this code answers the question and improves on the many upvoted answers the question already has, so that it is useful to other users with similar issues. Code-only answers are discouraged on Stack Overflow because they don't explain how it solves the problem. – FluffyKitten Sep 06 '20 at 01:06
7
const asynchronousFunction = async () => {
  // do something;
  // await something else;
}
Audu Moses
  • 71
  • 1
  • 2
3

For a static async arrow function, it works like this:

static myFunction = async () => {
    // your code here
}
loic.isaac
  • 31
  • 3
2

Most simplest way

   const MyFunction = async ()=>{
      // do something here
   }