简体   繁体   中英

conditionally make the 2nd axios call happen based on a first

I'm trying to make it so that I can look at the returned object from the first axios call, and if empty, continue to the 2nd (if it's not empty I will craft an error message)

Basically, the 2nd axios call should only happen if the userStatus object is empty. Both axios calls work independently but how Can I properly make this work so that I can hit the 2nd call if the object is empty?

Currently I get a 200 on the first axios call and an empty userStatus object in my console but the 2nd call doesn't happen

changeStatus: function(event) {

  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
  .then((response) => {
      this.userStatus = response.data
  })

  if(this.userStatus.length < 1){

    let data = {
        id: event.id,
        status: 'A'
    };

    axios.post('/status/change',data)
    .then((response) => {
        if (response.data.success == false) {
            this.errors = [];
            const errorLog = Object.entries(response.data.errors);
            for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
            }
        }
    })


  }else{
    console.dir('No');
  }
},

The issue is that your code is being executed synchronously (essentially line-by-line), while axios calls are a synchronous . So while your first axios call is still executing in the background, the statement if(this.userStatus.length < 1) gets evaluated – before your first call has returned.

If your second call is conditioned upon the result of your first call, you would need to make your second call inside the .then() handler of your first call:

changeStatus: function(event) {
  let user = this.auth_user;

  axios.get('/user/' + user + '/status')
    .then((response) => {
      this.userStatus = response.data;

      if(this.userStatus.length < 1) {
        let data = {
          id: event.id,
          status: 'A'
        };

        axios.post('/status/change',data)
          .then((response) => {
            if (response.data.success == false) {
              this.errors = [];
              const errorLog = Object.entries(response.data.errors);

              for (var i = errorLog.length - 1; i >= 0; i--) {
                console.log(errorLog[i][1][0]);
                this.errors.push(errorLog[i][1][0]);
              }
            }
          });
       } else {
         console.dir('No');
       }
    });
},

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