J.O
J.O

Reputation: 117

How to properly await Nuxt calls with async/await or .then

Im trying to fetch an API using chaining with .then but I don't figure it out I try like:

async fetch() {
  let path = this.$nuxt.context.route.path

  this.response = await axios.get(
   `/api${path}`,
   
  {
    headers: {
      'X-AUTH-TOKEN': process.env.SECURE_TOKEN, 
      'Content-Type': 'application/json'
    }
  }
).then((res) => {
  this.results = res.data.content.slice(0,40);
    return results();
  })
  .then((res) => {
  this.results2 = res.data.content.slice(20,40);
    return results2();
  })
},

For my API data load: when results is finish /results2 start to load, for using it with $fetchState.pending

What will be the best way of doing it? I'm trying to adapt the answer from here but no success so far.

Upvotes: 1

Views: 1408

Answers (1)

kissu
kissu

Reputation: 46676

This kind of code should be working fine

<script>
export default {
  async fetch() {
    this.response = await axios
      .get(`/api${this.$route.path}`, { // faster than this.$nuxt.context.route.path
        headers: {
          'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
          'Content-Type': 'application/json',
        },
      })
      .then((res) => { // ❌ this is useless because you're already using await above
        const results = res.data.content.slice(0, 40)
        return results()
      })
      .then((res) => { // ❌ this is useless because `slice` is NOT async
        const results2 = res.data.content.slice(20, 40)
        return results2()
      })
  },
}
</script>

Otherwise, I can also recommend a better approach overall, using async/await and not mixing it with .then at all, like this

<script>
export default {
  async fetch() {
    const response = await axios.get(
      `/api${this.$route.path}`,

      {
        headers: {
          'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
          'Content-Type': 'application/json',
        },
      }
    )
    const results = response.data.content.slice(0, 40)
    const results2 = results.data.content.slice(20, 40)
  },
}
</script>

PS: note that some things are not async, hence do not need await (or .then at all).


It can even be shorten to the following

<script>
export default {
  async fetch() {
    const response = await this.$axios.$get( // 👈🏻 using the shortcut $get
      `/api${this.$route.path}`,

      {
        headers: {
          'X-AUTH-TOKEN': process.env.SECURE_TOKEN,
          'Content-Type': 'application/json',
        },
      }
    )
    const results = response.content.slice(0, 40) // 👈🏻 no need for `.data` here
    const results2 = results.content.slice(20, 40) // 👈🏻 same here
  },
}
</script>

Thanks to the shortcuts available with the axios module that you should be using anyway.


As of why you should use async/await, it's just more lisible and available everywhere already (IE is dead). Here is some more info about the whole async/await thing: https://javascript.info/async-await

Far prettier than this kind of syntax (also named callback hell)

enter image description here

Upvotes: 2

Related Questions