【问题标题】:"await is a reserved word" when converting a promise to an await call [duplicate]将承诺转换为等待调用时“等待是保留字”[重复]
【发布时间】:2018-12-25 16:33:46
【问题描述】:

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

// 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 来摆脱 promise,像这样:

  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;

知道我做错了什么吗?

【问题讨论】:

  • 我在提问之前看到了重复的答案,现在我意识到这确实是正确的答案,但是给出的例子和解释似乎更难理解,我认为这个答案更加清晰和容易跟随。

标签: javascript async-await


【解决方案1】:

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

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

【讨论】:

  • 也许你可以用try catch 块让它变得更好
猜你喜欢
  • 2019-04-29
  • 2021-05-17
  • 1970-01-01
  • 2018-04-17
  • 2013-09-16
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
  • 2020-07-19
相关资源
最近更新 更多