0

I have the REST Api and response looks like this:

{
  "wordText" : "hello",
  "transcription" : "[həˈloʊ]",
  "pronunciation" : null,
  "picture" : null,
  "_links" : {
    "self" : {
      "href" : "http://localhost:8081/api/words/1"
    },
    "word" : {
      "href" : "http://localhost:8081/api/words/1"
    },
    "examples" : {
      "href" : "http://localhost:8081/api/words/1/examples"
    },
    "translates" : {
      "href" : "http://localhost:8081/api/words/1/translates"
    },
    "wordSet" : {
      "href" : "http://localhost:8081/api/words/1/wordSet"
    }
  }
}

And I want to get word and after that to load translates using link in body. My current code:

let wordlist = [];
      Vue.axios.get('/wordsets/1/words').then(response => {
          return response.data._embedded.words;
      }).then(words => {
        words.map(word => {
          wordlist.push(word)
        })
        //commit('LOAD_WORD_LIST', words);
      })

      wordlist.map(word => {
        Vue.axios.get(word._links.translates.href).then(response => {
          word.translates = response.data._embedded.translates;
          return word;
        })
      })

      console.log(wordlist);

But wordlist doesn't changed... Also I tried to execute another axios call in then() function, but the word.translates is underfind

Dev9567485
  • 55
  • 1
  • 1
  • 8
  • You cannot expect an asynchronous result (that comes in some future) to somehow be available *now* when you do `console.log`. You need to stick to the asynchronous pattern, and keep doing `then` `then` and `then`. Or `async` `await`... – trincot Feb 25 '19 at 18:06

1 Answers1

0

When you map over you wordlist it is still an empty array, because this

Vue.axios.get('/wordsets/1/words').then(response => {
          return response.data._embedded.words;
      }).then(words => {
        words.map(word => {
          wordlist.push(word)
        })
      })

is asynchronous and this

wordlist.map(word => {
        Vue.axios.get(word._links.translates.href).then(response => {
          word.translates = response.data._embedded.translates;
          return word;
        })
      })

is a synchronous map

Try running it this way

Vue.axios.get('/wordsets/1/words').then(response => {
    return response.data._embedded.words;
}).then(words => {
  return Promise.all(words.map(word => {
    return Vue.axios.get(word._links.translates.href)
    })
  )
}).then((response) => console.log(response))

This snippet will do just what you wanted, get the translations, try running it, it should console.log them all. But this is messy so I really advise into async/await approach, it can make it more readable

George.S
  • 149
  • 8