在循环中使用axios进行多个get请求的最佳方法是什么?

问题描述 投票:3回答:3

我在循环中发出多个请求时遇到问题。

我正在做一个反应应用程序,呈现多个组件称为卡。在每张卡片里面,我想提出一些要求,所以我得到了这个。

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

电影是我从父组件获得的数组。所以显然是有效的,因为我得到的结果,但山雀总是与最后一张牌的最后一个元素。这是一张图片:

Look, Even the item is changing (those tt....) I always get the last responde, what can I do ?

reactjs request axios
3个回答
1
投票

你可以使用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)
    }
}

1
投票

当你真的需要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


-1
投票

你尝试过使用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))
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.