How to ensure that Promise is resolved?

Asked

Viewed 42 times

0

Great, I’m trying to make a wish POST that in case of failure returns false and in case of success returns true.

My problem is because even with the await does not expect that the Promise is resolved to return the value to the variable.

async login() {
    this.userExist = await this.$root.login(this.email, this.password);
    console.log("User -> " + this.userExist);
}

The variable always takes the value of undefined.

The function this.$root.login() is in the file vue.js, and the function login is in a component.

login(email, password) {
    axios.post('/api/login',{email: email, password: password})
        .then(response => {
            sessionStorage.setItem('token', response.data.access_token);
            this.$store.commit('define', response.data.access_token);
            this.$router.push('/');
            return true;
        })
        .catch(error => {
            console.log(error);
            return false;
        });
}

1 answer

1


Its function this.$root.login need to return to Promise’s axios, in that way await can take the returns of Fulfill and Reject of your Prime correctly.

See the example below:

/* Se `success` for true requisição OK (200)
   Senão retorna erro 400 */
async function getUser(success) {
    let http_code = success ? 200 : 400;
    
    return axios.get(`https://httpbin.org/status/${http_code}`)
        .then(response => true)
        .catch(error => false)
}


async function login() {
    let userExists = await getUser(true);
    console.log("userExists == ", userExists);
    
    userExists = await getUser(false);
    console.log("userExists == ", userExists);
}

login();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.