react项目中如何解决同时需要多个请求问题

 

 


 

在工作中,遇到一个需求,需要展示一个列表,第一次请求只有列表的名字,需要在知道名字的情况下,再去请求每个列表的详细信息,然后展示完整的列表信息。

经过一番研究,发现多重的请求写在页面的方法里比较好实现。其他的在effects和servers里都不太好实现。

首先我们在 componentDidMount这个生命周期里进行操作:

在dispatch请求后,在.then中获取上一个请求返回的数据。然后做逐一请求的动作。
componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'release/fetchAnnounce',
      payload: {
        cluster:"guanwang"
      },
    }).then((data)=>{
      this.newResults(data)
    })
  };
 

newResults方法 的书写:

Promise.all的讲解
 newResults=(data)=>{
    const newData=[];
    data.map(item=>{
      newData.push(...item)
    })
   // 异步操作,需要等待所有的请求接口完成以后,拿到全部的数据去使用
    const newResult=async ()=> {
      await Promise.all(
        newData.map((item, index) => {
          return   request(
            `/api/v1/admin/rule-set/list`
          ).then(r => {
            const val=
              {
                id: index + 1,
                ...r.data[0],
                ...item
              };
            return val
          })
        })
      ).then((values)=>{
        this.setState({releaseVal:values})
      })
    }
    newResult()
  };

 

Promise.all的讲解

Promise.all在处理异步请求很有用。举个例子:

let q1 = new Promise((resolve, reject) => {
  resolve('处理成功了')
})

let q2 = new Promise((resolve, reject) => {
  resolve('success')
})

let q3 = Promse.reject('error')

Promise.all([q1, q2]).then((res) => {
  console.log(res)               //['处理成功了', 'success']
}).catch((error) => {
  console.log(error)
})

Promise.all([q1,q3,q2]).then((res) => {
  console.log(res)
}).catch((error) => {
  console.log(error)      // 失败了,打出 'error'
})

 

它可以让你等待所有的操作完成后进行操作,而且它完成的返回结果是按 q1,q2,q3的顺序来的。不会因为p2的结果先出来就排在最前面。

知道Promise.all,就相对于的可以了解一下Promise.race

Promise.race的使用方法和Promise.all差不多。唯一的不同就是返回的顺序不同,Promise.race是按照运行的先后顺序进行排列的。假如q2先完成,q2的返回就会排在最前面。

 

posted @ 2022-01-07 17:57  荷风伊夏  阅读(1559)  评论(0编辑  收藏  举报