我在循环中发出多个请求时遇到问题。
我正在做一个反应应用程序,呈现多个组件称为卡。在每张卡片里面,我想提出一些要求,所以我得到了这个。
componentWillMount(){
if(this.props.movies){
let promises = []
this.props.movies.forEach((item, i) => {
console.log(item)
let movieUrl = `http://localhost:3000/movies/${item}`
promises.push(axios.get(movieUrl))
})
axios.all(promises).then(res => console.log(res))
}
}
电影是我从父组件获得的数组。所以显然是有效的,因为我得到的结果,但山雀总是与最后一张牌的最后一个元素。这是一张图片:
你可以使用async/await
。看:
async componentWillMount(){
if(this.props.movies){
const results = []
this.props.movies.forEach((item, i) => {
const movieUrl = `http://localhost:3000/movies/${item}`
const result = await axios.get(movieUrl)
results.push(result)
})
// console.log(results)
}
}
当你真的需要forEach
并使用map
而不是item.imdbID
构建网址时,你应该避免使用item
componentWillMount(){
if(this.props.movies){
const promises = this.props.movies.map(item => {
const movieUrl = `http://localhost:3000/movies/${item.imdbID}`
console.log(movieUrl)
return axios.get(movieUrl)
)
Promise.all(promises).then(results => console.log(results))
}
}
Edit1:由于不兼容的构建配置而删除了异步/等待编辑2:使用item.imdbID
而不是item
和已记录的URL
你尝试过使用bluebird的Promise.mapSeries吗?
import Promise from 'bluebird'
componentWillMount(){
if(this.props.movies){
Promise.resolve(this.props.movies)
.mapSeries(item => axios.get(`http://localhost:3000/movies/${item}`))
.then(movies => console.log(movies))
}
}