How to run a function only after a Javascript API call?

Asked

Viewed 54 times

-1

I’m stuck in a situation here which is as follows:

The project is done in React

import hostApi from "api/hostApi";

const body = {
    token: localStorage.getItem("suavagaToken")
}

function isAuthenticated() {
    console.log("Chamou a função");
    hostApi.post("empresa/isAuthenticated", body)
        .then(response => {
            localStorage.setItem("suavagaUserIsAuth", response.data)
            console.log("Atualizou o isAuth");
        })
        .catch(err => {
            console.error("Erro ao verificar se a empresa está autenticada! :" + err)
        })
}

export default isAuthenticated;
function checkRouteAuth() {
    isAuthenticated();

    let aux = localStorage.getItem("suavagaUserIsAuth");

    console.log("Variavel aux = " + aux);
    if (aux === "true") {
        return true;

    } else {
        return false;
    }
}

I need to get my checkRouteAuth() function to continue running only after isAuthenticated() is over. I put the console.log to see the execution sequence and the following appears:

Chamou a função         auth.js:8
Variavel aux = false    Routes.jsx:14
Atualizou o isAuth      auth.js:12 

That is, the log "Updated isAuth" is running before the "Variable aux" so aux does not update at runtime. How to solve this?

  • Here’s an article that can help you https://imasters.com.br/front-end/entenda-tudo-sobre-asyncawait

  • You can also take a look at promise chaining.

  • I still don’t understand what it would be like to put async/await in my code

1 answer

1

Could use async/await so that the rest of the function checkRouteAuth() awaits the conclusion of isAuthenticated().

async function checkRouteAuth() {
    await isAuthenticated();

    let aux = localStorage.getItem("suavagaUserIsAuth");

    console.log("Variavel aux = " + aux);
    if (aux === "true") {
        return true;

    } else {
        return false;
    }
}

Remembering that this means your function checkRouteAuth() would now return a Promise<boolean>.

Updating

He would also have to return to Promise return hostApi.post... within the function isAuthenticated()

  • Did not change the result and still appears the annotation "'await' has no Effect on the type of this Expression" no await

  • Has to make isAuthenticated() async and within checkRouteAuth() awaiting.

  • ta right could also. Could also put return hostApi.post... inside isAuthenticated()

  • @Augustovasques updated my answer, put Await in the wrong function

  • Still need to modify this function function isAuthenticated() and its signature.

  • 1

    @Augustovasques do not need to place await in isAuthenticated(). async/await basically only returns a promise. We are already returned a isAuthenticated() if we put return hostApi.post...

Show 1 more comment

Browser other questions tagged

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