首页 > 解决方案 > 循环中的axios请求

问题描述

我有 REST Api,响应如下所示:

{
  "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"
    }
  }
}

我想得到消息,然后使用正文中的链接加载翻译。我当前的代码:

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);

wordlist没有改变......我也尝试在then()函数中执行另一个 axios 调用,但是word.translatesunderfind

标签: javascriptecmascript-6axios

解决方案


当您映射到您的单词列表时,它仍然是一个空数组,因为这

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

是异步的,这

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

是同步映射

试试这样运行

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))

这个片段会做你想要的,得到翻译,尝试运行它,它应该控制台.记录它们。但这很混乱,所以我真的建议使用async/await方法,它可以使它更具可读性


推荐阅读