【发布时间】: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;
知道我做错了什么吗?
【问题讨论】:
-
我在提问之前看到了重复的答案,现在我意识到这确实是正确的答案,但是给出的例子和解释似乎更难理解,我认为这个答案更加清晰和容易跟随。