先看一段代码(Vue):
methods: {
async getAll() {
const a = await getAllModifiedPlans()
console.log('a;', a)
return a
}
},
created() {
const result = this.getAll()
console.log('r:', result)
}
直接调用 this.getAll(),我们期望返回 a 的值,但实际不是这样的结果
这里注意几个概念:
1. async 函数的返回值是一个 promise
2. async 里面的 return 值不是给外部的返回值,而是 promise 的 resolved 值
3. await promise 得到 resolved 值
methods: {
async getAll() {
const a = await getAllModifiedPlans()
console.log('a:', a)
return a
}
},
created() {
const result = this.getAll()
console.log('r:', result)
}
输出:
r: Promise {<pending>}
a: {code: 0, message: "success", data: Array(2)}
可以看到 result 会立刻得到一个 promise
解决:
methods: {
async getAll() {
return await getAllModifiedPlans()
}
},
async created() {
const result = await this.getAll()
console.log(result)
}