Я новичок в ES7
Я хочу использовать async/await в Vue.js
Вот мой код
created (){
this.getA()
console.info(2)
this.getB()
},
methods : {
getA (){
console.info(1)
},
getB (){
console.info(3)
}
}
Он возвращается
1
2
3
Но когда я использую его с аксиомами, то
created (){
this.getA()
console.info(2)
this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.info(1)
})
},
getB (){
console.info(3)
}
}
Он возвращается
2
3
1
Поэтому я хочу добавить async/await в этот код.
Как я могу использовать async/await?
Я старался
async created (){
await this.getA()
console.info(2)
await this.getB()
},
methods : {
getA (){
$axios.post(`/getA`,params){
.then((result) => {
console.info(1)
})
},
getB (){
console.info(3)
}
}
Он возвращает тот же результат.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


попробуй это
async created (){
let resultFromgetA = await this.getA()
console.info(2)
await this.getB()
},
methods : {
getA :() =>{
return $axios.post(`/getA`,params);
},
getB : async() =>{
//use await key with async calls
console.info(3)
}
}
Вы должны использовать либо then, либо await, а не оба, как показано ниже:
При использовании then
created () {
this.getA().then((result) => {
console.info(1)
console.info(2)
this.getB()
})
},
methods : {
getA () {
return $axios.post(`/getA`,params);
},
getB (){
console.info(3)
}
}
При использовании await
async created (){
await this.getA()
console.info(1)
console.info(2)
this.getB()
},
methods : {
getA : async() => {
return $axios.post(`/getA`,params);
},
getB : () => {
console.info(3)
}
}
Обратите внимание, что при вызове getB() вам не нужны then или await, поскольку он не асинхронный.
поскольку getB не является асинхронным, то какая польза от async для getB?
В отличие от того, что сказал @thanthu, вы можете использовать как then, так и await.
В своем первом посте вы пропустили только добавление return в метод getA:
async created (){
await this.getA()
console.info(2)
await this.getB()
},
methods : {
getA() {
return $axios
.post(`/getA`,params){
.then((result) => {
console.info(1)
});
},
getB() {
console.info(3)
}
}
ты сможешь. Но должны ли вы? однажды вы окажетесь посреди блоков try-catch и .catch(err => {console.info(err)}) с кучей инструкций async-await, .then и .all. Это может быть вторым по сложности испытанием для джентльмена. Разумеется, после попытки родить ребенка. Для женщин - самый сложный.
это все еще похоже на путь, вы ожидание для обещания, которое заканчивается, когда console.info(1) выполняется
Вуэйс, пример с запросом API Аксиос. подробнее между кодом
methods: {
async getA(data, type) {
console.info("This is a API calls, that the response time is vary.");
const result = await this.getSources();
console.info("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');
});
});
},
},
getAне возвращает обещанное.