2๐
You should first understand the fundamental of how Async/Await
is different from Promises
.
Async/Await: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function
Promises: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
This is an example of a Promise
:
someFunction().then((result)=>{
/*Your logic*/
}).catch(()=>{
/*Error handle*/
})
This is an example of a Async/Await
:
try{
let result = await someFunction()
/*Your logic*/
}catch(err){
/*Error handle*/
}
If you gonna use Async/Await
with axios
:
let response = await axios.post()
//The program will wait until response got its result.
let user = response.data.results
1๐
Returning in the chained .then()
method does not resolve the promise. You can wrap your axios in a Promise()
object and resolve/reject based on the response:
goLogin(password){
return new Promise((resolve, reject) => {
axios.post(appRoute+'user/login',{ pwd: password })
.then(data => {
var user = ;
resolve({ token: data.data.results });
})
.catch(err => {
reject({ errorMessage: err.message });
})
});
}
0๐
I resolved in this manner:
In this way, I can make more complex result and the pending promise in vue side is resolve correctly like above in login.vue
--> login.js function
async goLogin(password){
let result
await axios.post(appRoute+'user/login',{pwd:password})
.then(data=>{
console.log(data)
result = { token: data.data.results }})
.catch(err=>{
result= {errorMessage:err.message}})
return result
}
}
Added on behalf of the question author.