4

I have the following code that works ok:

// api.js
export default {
    async readAsync (resource) {
        await new Promise(r => setTimeout(r, 400));
        return data[resource];
    },
}

// ProductList.vue
import api from '@/services/api'

[...]

  methods: {
    fetch () {
      this.loading = true;
      api.readAsync('products').then(data => {
        this.products = data;
        this.loading = false;
      });
    }
  }

[...]

I want to use await to get rid of the promise, like this:

  methods: {
    fetch () {
      this.loading = true;
      this.products = await api.readAsync('products');;
      this.loading = false;
    }
  }

But I get the following error:

Module build failed (from ./node_modules/babel-loader/lib/index.js): 
SyntaxError: D:\devel\apps\vue-tests\cli-test\src\components\ProductList.vue: await is a reserved word (59:22)
  57 | this.loading = true;
  58 | 
> 59 | this.products = await api.readAsync('products');; 
     |                 ^ 
  60 | this.loading = false;

Any idea what could I be doing wrong?

opensas
  • 60,462
  • 79
  • 252
  • 386
  • 1
    I saw the duplicate answer before asking, and now I realize that indeed is the correct answer, nevertheless the example given and the explanation seems more difficult to follow, I think this answer is far more clear and easy to follow. – opensas Jul 17 '18 at 21:37

1 Answers1

5

You need to declare your fetch method as async in order to use the await keyword:

async fetch () {
  this.loading = true;
  this.products = await api.readAsync('products');;
  this.loading = false;
}
AJC24
  • 3,280
  • 2
  • 19
  • 30