Skip to main content
  1. About
  2. For Teams
Asked
Viewed 744k times
952

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?

12
  • 2
    It's worth noting that at least firefox and babel does let you do that
    Jaromanda X
    –  Jaromanda X
    2017-03-22 22:55:41 +00:00
    Commented Mar 22, 2017 at 22:55
  • 42
    var foo = async () => await Promise.resolve('ha'); - works just fine
    Jaromanda X
    –  Jaromanda X
    2017-03-22 22:56:39 +00:00
    Commented Mar 22, 2017 at 22:56
  • 3
    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
    –  Jaromanda X
    2017-03-22 22:57:54 +00:00
    Commented Mar 22, 2017 at 22:57
  • 1
    that may well be @Pointy, but it does work natively in current firefox and chrome and node.js (7.7.4)
    Jaromanda X
    –  Jaromanda X
    2017-03-22 22:59:59 +00:00
    Commented Mar 22, 2017 at 22:59
  • 1
    The ES2017 spec has a section on async arrow function definitions @Pointy.
    Heretic Monkey
    –  Heretic Monkey
    2017-03-22 23:05:15 +00:00
    Commented Mar 22, 2017 at 23:05

11 Answers 11

1630

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
}
Sign up to request clarification or add additional context in comments.

11 Comments

The OP appears to be looking for a named, async, arrow function which is the one syntax you do not show.
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.
@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 since ES2015 when you do const foo = async () => {} the name of the function is set to foo - ecma-international.org/ecma-262/6.0/… and ecma-international.org/ecma-262/6.0/… - see discussion in esdiscuss.org/topic/…
@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.)
|
153

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

3 Comments

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

Immediately Invoked Async Arrow Function:

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

Immediately Invoked Async Function Expression:

(async function () {
    console.log(await asyncFunction());
})();

2 Comments

That's the one i was looking for
26
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');

Comments

22

Async Arrow function syntax with parameters

const myFunction = async (a, b, c) => {
   // Code here
}

Comments

22

Basic Example

folder = async () => {
    let fold = await getFold();
    //await localStorage.save('folder');
    return fold;
  };

Comments

16

You may also do:

 YourAsyncFunctionName = async (value) => {

    /* Code goes here */

}

2 Comments

with one param you don't need parenthesis. YourAsyncFunctionName = async value => { /* Code goes here */ }
@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
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);
});
}

1 Comment

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.
7
const asynchronousFunction = async () => {
  // do something;
  // await something else;
}

Comments

3

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

static myFunction = async () => {
    // your code here
}

Comments

2

Most simplest way

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

Comments

Your Answer

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.