-1

I am trying to make a form, where users can change their email address of the account. I want them to enter their password to validate them. So I have a function that is doing the email change, but before it calls the validate function. If the return value is true it goes on. If not an error appears. But when testing it with the correct credentials it always goes into the else although i get a valid axios response.

    emailChange() {
      if (this.validate() == true) {
        var data = JSON.stringify({
          email: this.email,
        });
        this.put(data);
      } else {
        this.error = "Falsches Passwort";
        this.snackbar = true;
      }
    },

    validate() {
      var data = JSON.stringify({
        identifier: this.loggedInUser.email,
        password: "123456",
      });

      var config = {
        method: "post",
        url: "http://192.168.190.112:1337/api/auth/local",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          return true;
        })
        .catch(function (error) {
          console.log(error);
        });
    },
  • Does this answer your question? [How do I return the response from an asynchronous call?](https://stackoverflow.com/q/14220321/328193) – David Oct 20 '22 at 18:18
  • Hm not really as I am using ```then``` in my function. – Goldenfaeron Oct 20 '22 at 18:26
  • "Using `then`" is not a magic wand. The `return` in your `then` callback is returning from *that* callback function, not from your `validate` function. The `validate` function *itself* never returns anything. You have an asynchronous operation. Either make use of Promises (making `validate` also `async` and return the Axios `Promise`) or introduce a callback structure for your operation. Refer to the proposed duplicate more carefully. – David Oct 20 '22 at 18:29
  • Ah got it now. Thanks for the quick help. :) – Goldenfaeron Oct 20 '22 at 18:31

2 Answers2

0

The function return is not returning to validate. Axios is asynchronous and you need either a promise or a callback.

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          return true; // this does not return to validate(). it returns just here
        })
        .catch(function (error) {
          console.log(error);
        });

This is a way to implement it.

    emailChange() {
      this.validate((error, isValid) => {
        if (isValid) {
          var data = JSON.stringify({
            email: this.email,
          });
          this.put(data);
        } else {
          this.error = "Falsches Passwort";
          this.snackbar = true;
        }
      })
    },

    validate(callback) {
      var data = JSON.stringify({
        identifier: this.loggedInUser.email,
        password: "123456",
      });

      var config = {
        method: "post",
        url: "http://192.168.190.112:1337/api/auth/local",
        headers: {
          "Content-Type": "application/json",
        },
        data: data,
      };

      this.$axios(config)
        .then(function (response) {
          console.log(JSON.stringify(response.data));
        })
        .then(function () {
          callback(null, true);
        })
        .catch(function (error) {
          callback(error);
        });
    }
OFRBG
  • 1,653
  • 14
  • 28
0

I think you're misunderstanding the purpose of .then().

Creating a request isn't instant, and it's completion depends on the server you're requesting data from to send you back a response. Because of this, axios uses asynchronous code to give you a Promise that will resolve after the request is complete.

The callback within the .then() function is called whenever the request is resolved (which could take multiple seconds with a slow connection).

The callback that contains your return statement could be called multiple seconds after your validate function ends, which isn't what you want.

I'd suggest using async/await as an alternative.

Declaring a function as async makes it return a Promise no matter what, which is what you want, and await waits for a promise to resolve before continuing.

Here's a quick example

// This function returns a promise!
async validate() {
  // axios.get() returns a promise, so we use await to wait until it's resolved
  let response = await axios.get("url") 

  // return the data (this is not a promise)
  // since the method is async, this will be automatically converted into a promise
  // that will resolve when the method returns something
  return response;
}

// you can only use "await" in async functions
async emailChange() {
  // wait until this.validate() is finished before continuing
  if(await this.validate() == true) {
    // etc.
  }
}

async/await is generally the preferred way to do this because it's much cleaner than chaining callbacks together with .then()

Hopefully this helps

zmehall
  • 557
  • 3
  • 13