首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >将promise转换为await调用时,"await is a reserved word“

将promise转换为await调用时,"await is a reserved word“
EN

Stack Overflow用户
提问于 2018-07-18 05:27:27
回答 1查看 5.2K关注 0票数 4

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

代码语言:javascript
复制
// 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去掉这个承诺,就像这样:

代码语言:javascript
复制
  methods: {
    fetch () {
      this.loading = true;
      this.products = await api.readAsync('products');;
      this.loading = false;
    }
  }

但我得到以下错误:

代码语言:javascript
复制
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;

你知道我会做错什么吗?

EN

回答 1

Stack Overflow用户

发布于 2018-07-18 05:29:18

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

代码语言:javascript
复制
async fetch () {
  this.loading = true;
  this.products = await api.readAsync('products');;
  this.loading = false;
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51390435

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档