user5067291
user5067291

Reputation: 449

Access promise value axios

I'm trying to access the promise value from an Axios call from another function.

methods: {
    checkItem() {
        const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
        return axios.get(url)
            .then(response => response.status);
    },

    save() {
        console.log(this.checkItem());
    }
}

I'm expecting the status code to be logged in the console when I call save(). At the moment, it's logging the whole promise.

Upvotes: 0

Views: 999

Answers (3)

ahmed galal
ahmed galal

Reputation: 269

    this.checkItem().then(res => {
      console.log(res);
    });

Upvotes: 0

Andrew Vasylchuk
Andrew Vasylchuk

Reputation: 4779

You can use async/await.

<script>
new Vue({
  el: "#root",

  methods: {
    checkItem() {
      const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
      return axios.get(url).then(response => response.status);
    }
  },
  async save() {
    console.log(await this.checkItem());
  }
});
</script>

Or using Promise:

<script>
new Vue({
  el: "#root",

  methods: {
    checkItem() {
      const url = "http://api.crossref.org/journals/" + this.editedItem.issn;
      return axios.get(url).then(response => response.status);
    }
  },
  save() {
    this.checkItem().then(res => {
      console.log(res);
    });
  }
});
</script>

Upvotes: 2

bart
bart

Reputation: 145

Change your save() function to the following:

async save() {
  const response = await this.checkItem()
  console.log(response);
  // The status code is likely in something like response.status
}

Upvotes: 0

Related Questions