简体   繁体   中英

Javascript Callback Not Working as Intended

I am trying to ensure that checkteamexists only executes after checklogin has executed. However, checkteamexists still functions after checklogin .

You can imagine teamhome1_message and teamhome2_message as alert dialogs. They pop a message up and didn't return anything.

function pushhistory(url, callback) {
  history.push(url);
  callback();
}

function checklogin(callback) {
  if (!state.user.authenticated) {
    pushhistory("/accounts/login", function() {
      teamhome2_message()
    });
  }
  callback();
}

function checkteamexists(teamname) {
  if (teamname.toString().toLowerCase() == "team1") {
    teamid = 1;
  }
  else {
    pushhistory("/", function() {
      teamhome1_message()
    });
  }
}

useEffect(() => {
  checklogin(function() {
    checkteamexists(teamname);
  })
}, []);

checklogin worked because the URL became /accounts/login and prompted teamhome2_message . However, teamhome1_message still appeared even though I don't want it to.

I tried specifying a callback in the useEffect hook (which is specific to React) but the callback didn't seem to work either. Can anyone please point out the problem?

Thanks in advance.

@p2pdops had the right solution: put the callback function in the else block.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM