USE*_*SER 4 javascript async-await vue.js ecmascript-2017
我是ES7的新手
我想在Vue.js中使用async / await
这是我的代码
created (){
this.getA()
console.log(2)
this.getB()
},
methods : {
getA (){
console.log(1)
},
getB (){
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
它返回
1
2
3
Run Code Online (Sandbox Code Playgroud)
但是当我与axios一起使用时
created (){
this.getA()
console.log(2)
this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.log(1)
})
},
getB (){
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
它返回
2
3
1
Run Code Online (Sandbox Code Playgroud)
所以我想在该代码中添加异步/等待。
如何使用异步/等待?
我试过了
async created (){
await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.log(1)
})
},
getB (){
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
它返回相同的结果。
小智 13
与@thanthu 所说的不同,您可以同时使用 then 和 await。在你的第一篇文章,你只错过了添加return的getA方法:
async created (){
await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA() {
return $axios
.post(`/getA`,params){
.then((result) => {
console.log(1)
});
},
getB() {
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
您必须同时使用then或await不使用两者,如belwo所示:
如果使用 then
created () {
this.getA().then((result) => {
console.log(1)
console.log(2)
this.getB()
})
},
methods : {
getA () {
return $axios.post(`/getA`,params);
},
getB (){
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
如果使用 await
async created (){
await this.getA()
console.log(1)
console.log(2)
this.getB()
},
methods : {
getA : async() => {
return $axios.post(`/getA`,params);
},
getB : () => {
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,在调用getB()时不需要then或await由于它不是异步的
Vuejs,带有Axios API 请求的示例。代码之间的更多细节
methods: {
async getA(data, type) {
console.log("This is a API calls, that the response time is vary.");
const result = await this.getSources();
console.log("Do what you want after completing the prev job.");
},
getSources() {
return new Promise(resolve => {
// Here the point is the resolve that you should resolve('something');.
this.axios
.get("/api/sources")
.then((resp) => {
this.sources = resp.data;
resolve('resolved');
})
.catch(() => {
resolve('rejected');
});
});
},
},
Run Code Online (Sandbox Code Playgroud)
尝试这个
async created (){
let resultFromgetA = await this.getA()
console.log(2)
await this.getB()
},
methods : {
getA :() =>{
return $axios.post(`/getA`,params);
},
getB : async() =>{
//use await key with async calls
console.log(3)
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9114 次 |
| 最近记录: |