0

In my repository.js i have the following:

async getAllContactRequests() {
    return new Promise(() => {
      axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer " + sessionStorage.getItem("user_token") }
        })
    })
  }

In my Vue component i have:

<script>
import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      apiData: null,
    };
  },

  async mounted() {
    console.log("This prints");
    this.apiData  = await repository.getAllContactRequests().then(result => result.data);
    console.log("This doesn't print");
  },
};
</script>

I don't get the data from the promise, and every line after the call to the api function does not execute. What am i doing wrong?

4
  • 2
    The promise is never resolved. Do not return a new Promise, just return axios.get because it's a Promise already. You don't even need the async at all in that specific case (in the repository) Commented Sep 29, 2021 at 7:55
  • 1
    What is the explicit promise construction antipattern and how do I avoid it? Commented Sep 29, 2021 at 7:57
  • An additional note. When using await you in most cases don't need then. this.apiData = await repository.getAllContactRequests().then(result => result.data); can be written as this.apiData = (await repository.getAllContactRequests()).data; Commented Sep 29, 2021 at 7:57
  • AWESOMe! So far so good. Now, how do i actually access the data? The object is Promise, can i convert it to JSON somehow? or is there a better way? Commented Sep 29, 2021 at 8:05

1 Answer 1

1

Assuming the API returns JSON data, you can refactor the codes above into:

async getAllContactRequests() {
    return axios
        .get("http://127.0.0.1:8000/api/contactRequests", {
          headers: { "Authorization": "Bearer " + sessionStorage.getItem("user_token") }
        })
  }

This is because Axios returns Promise, and there is no need to redundantly wrap it into a Promise.

To consume the response data, you simply await for the API request:

import repository from "@/api/repository";

export default {
  name: "posts-index",

  data() {
    return {
      apiData: null,
    };
  },

  async mounted() {
    const response = await repository.getAllContactRequests()
    if (response && response.data) {
       this.apiData = response.data
    }
  },
};
Sign up to request clarification or add additional context in comments.

1 Comment

Should the getAllConectRequests() method have the async keyword if you aren't using await in the body of the function?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.