【发布时间】:2019-01-15 16:23:26
【问题描述】:
这一切都有效,除了每次我以不同的顺序得到结果。
例如。 2.name, 4.name, 1.name, 3.name, 5.name。
我怎样才能让每个 http req 在开始另一个之前完成,这样我才能像数组一样按顺序获得结果?
const array = [ '1', '2', '3', '4', '5' ]
array.forEach(el=>{
axios.get(`/item/${el}`)
.then(res=>{
console.log(res.data.name)
}
})
【问题讨论】:
-
您可以创建变量以保存为数组。示例 const dataName =[...包含 res.data.names]。之后,循环组合数字和名称
-
您可以在循环中使用 await,前提是您处于异步函数中,例如在 forEach 中,const res = await axios.get(...); console.log(res);
标签: javascript axios