循环中的Axios请求

时间:2019-02-25 17:23:11

标签: javascript ecmascript-6 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

1 个答案:

答案 0 :(得分:0)

当您在单词表上进行映射时,它仍然是一个空数组,因为这

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

此代码段将按照您的要求进行操作,获取翻译,然后尝试运行它,它应该进行console.log所有操作。但这很麻烦,因此我真的建议您使用 async / await 方法,使其更具可读性