javascript - 循环中的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.translates
是underfind
解决方案
当您映射到您的单词列表时,它仍然是一个空数组,因为这
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方法,它可以使它更具可读性
推荐阅读
- android - FloatingActionButton 中的图标位于右下角,似乎无法居中
- angular - 带参数的角延迟加载
- reportlab - ReportLab 段落中的字母间距
- html - Django 不显示图像并渲染 CSS
- php - 使用 Doctrine 2 DQL 查询具有大量数据的 LEFT JOIN 的最有效方法是什么
- gnuplot - gnuplot - 用户定义厚度的二维图
- mysql - 错误 1292 日期时间值不正确
- email - 使用 microsoft graph 放置/编辑 MIME 电子邮件内容
- node.js - 在 Asp.Net Core 2.1.0 中安装 fontawesome 5.2.0
- c - 让子进程暂停,直到收到父进程的信号以执行 execl 任务