如何使用Axios调用多个休息请求

时间:2018-05-17 12:52:43

标签: javascript reactjs rest axios

我是React JS的新手。我已经阅读了一些如何在Reactjs中创建客户端休息的例子 我的问题 - 我得到所有课程,然后我想要为每个课程调用另一个HTTP服务。我的代码如下。

export default class Courses extends Component{

    constructor(props) {
        super(props);
        this.state = {courses: []};
    }

    componentDidMount() {
        axios.get('http://localhost:8065/api/course/all')
        .then(response => {
            const courseList = response.data.map(c => {
                return {
                  id: c.id,
                  name: c.name,
                  previewBase64:c.previewBase64,
                  authors:
                     axios.get('http://localhost:8065/api/course/getAuthorsByCourseId/'+c.id+"/")
                    .then(res => {
                        const profiles = res.data.map(p => {
                            return {
                              name: p.name                       
                            };
                          })
                    })
                };
              })
              console.log(courseList);
              const newState = Object.assign({}, this.state, {
                courses: courseList
              });
              // store the new state object in the component's state
              this.setState(newState);
        }); 
    };
    render(){
        return(
            <CourseList courses={this.state.courses}/>
        )
    }
}

my CourseList.jsx:

const courseList = (props) => (
    <Grid>
    <Row>
        {
            props.courses.map((course, i)=>{
                return  (
                <Col key ={i} lg={2} sm={8} xs={12} md={6}>
                    <div className="course-block">
                         <p>{course.name}</p>
                         <p>AUTHOR NAME WILL BE HERE </p>
                    </div>

                </Col>)
                }) 
            }                             
    </Row>
</Grid>
);

export default courseList;

这段代码有效,但我对这样的作者有“承诺”。 {id:7,name:“HTML”,previewBase64:“”,authors:Promise}

3 个答案:

答案 0 :(得分:0)

您需要Promise.allaxios.all

L

答案 1 :(得分:0)

您可以尝试以下操作,将其用作参考https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function

async componentWillMount() {
        let data = await axios.get('http://localhost:8065/api/course/all').then(response => {
            return response
        })
        const courseList = data.map(c => {
            return {
                id: c.id,
                name: c.name,
                previewBase64: c.previewBase64,
                authors: await axios.get('http://localhost:8065/api/course/getAuthorsByCourseId/' + c.id + "/")
                    .then(res => {
                        const profiles = res.data.map(p => {
                            return {
                                name: p.name
                            };
                        })
                    })
            };
        })
        console.log(courseList);
        const newState = Object.assign({}, this.state, {
            courses: courseList
        });
        // store the new state object in the component's state
        this.setState(newState);
    }

答案 2 :(得分:0)

你可以尝试这种方式重构,无论如何只需要一个返回课程和作者的API就更好了

componentDidMount() {
    axios.get('http://localhost:8065/api/course/all')
    .then(response => {

      const promises = response.data.map(c => {
        axios.get('http://localhost:8065/api/course/getAuthorsByCourseId/'+c.id+"/")
        .then(res => { //for each course get the authors
            return res.data.map(p => {
                return {
                  name: p.name                       
                };
              });
        })
        .then(profiles => ({ id: c.id, profiles })); //keep a reference with the course
      });

      axios.all(promises, (allProfiles) => { //wait for all getAuthorsByCourseId are resolved
        const profileMap = allProfiles.reduce((map, profiles)=> {
          return map[profiles.id] = profiles.profiles;
        }, {}); // from array to map
        const courseList = response.data.map(c => {
          return {
            id: c.id,
            name: c.name,
            previewBase64:c.previewBase64,
            authors: profileMap[c.id],
          };
        }); //build the courseList with all data resolved
        const newState = Object.assign({}, this.state, {
          courses: courseList
        });
        // store the new state object in the component's state
        this.setState(newState);       
      });
    }); 
};