2

Why writing this is wrong:

'use strict'

async example1 () {
  return 'example 1'
}

async example2 () {
  return 'example 2'
}

export { example1, example2 }

But it is fine like this:

export default {
  async example1 () {
    return 'example 1'
  },
  async example2 () {
    return 'example 2'
  }
}

It is quite confusing. I assume the latter is wrong too.

Any explanations for this?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
Run
  • 54,938
  • 169
  • 450
  • 748

2 Answers2

4

The first tries (but fails) to declare multiple individual functions, while the second creates an object literal with several method definitions that is then default exported. Btw, it's the same without the async keyword. You'll want to use

export async function example1() {
  return 'example 1'
}

export async function example2() {
  return 'example 2'
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
4

This behaviour has nothing to do with async or export. It is part of ES6 enhanced object properties:

These are equivalent:

const foo = 123;
const a = {
  foo: foo,
  bar: function bar() { return 'bar'; },
  baz: async function baz() { return await something(); },
};

and

const foo = 123;
const a = {
  foo,
  bar() { return 'bar'; },
  async baz() { return await something(); },
};
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
Kos
  • 70,399
  • 25
  • 169
  • 233
  • thanks for this. can I do `baz: async baz() { return await something(); },`? – Run Aug 21 '17 at 15:59
  • 2
    @teelou: No. You need the `function` keyword to define functions (object method syntax and arrow functions are the exceptions). So you could do `baz: async function() {...}` or `baz: async () => {...}` or `baz: async function baz() {...}`. – Felix Kling Aug 21 '17 at 16:05
  • @FelixKling thanks. `object method syntax and arrow functions are the exceptions` - fair enough... – Run Aug 21 '17 at 17:05