0

I'm working on Nuxt.js app and try to use an async method to get data from api, but the result of the async method is always undefined. It looks like my methods aren't waiting for the response. I don't know what I've missed.
Here is my code in methods: {..}

async getSomething() {
  console.log("getSomething");
  if (condition) {
    axios
      .get("api_url")
      .then((response) => {
        console.log("getSomething success");
        return "success";
      })
      .catch((error) => {
        console.log("getSomething fail 1");
        return "fail";
      });
  } else {
    console.log("getSomething fail 2");
    return "fail";
  }
}
doSomething() {
  console.log("do Something");
  this.getSomething().then((result) => {
    console.log("result", result);
    if (result === "success") {
      // do something on success
    } else {
      // do something on fail
    }
  });
  console.log("end doSomething");
}

I already try to logging this.getSomething() and the result is Promise {<pending>}
Here, when a method has been call on created () {..}

this.doSomething()
// doSomething
// getSomething
// end doSomething
// getSomething success
// result undefined

Lioness100
  • 8,260
  • 6
  • 18
  • 49

1 Answers1

3

I think part of your problem is that you're mixing async/await style of writing code with promise-chaining style. When you return 'fail' or 'success', you're usually returning from the axios.get callback, not from the getSomething method. You might want to rewrite your code a little like this:

async getSomething () {
    console.log('getSomething')
    if (condition) {
        try {
            let response = await axios.get('api_url')
            console.log('getSomething success')
            return 'success'
        } 
        catch(error) {
            console.log('getSomething fail 1')
            return 'fail'
        }
    } else {
        console.log('getSomething fail 2')
        return 'fail'
    }
}
Raphael Serota
  • 2,157
  • 10
  • 17