将promise转换为await呼叫时,“ await是保留字”

时间:2018-07-17 21:27:27

标签: javascript async-await

我有以下可以正常工作的代码:

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

[...]

我想使用await摆脱承诺,像这样:

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

但是出现以下错误:

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;

任何想法我会做错什么吗?

1 个答案:

答案 0 :(得分:3)

您需要将fetch方法声明为async才能使用await关键字:

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