兑现所有承诺

时间:2018-07-25 18:15:02

标签: javascript reactjs axios

我正在尝试等待解析第一个Promise,然后解析两个异步Promise,然后从所有先前的Promise中解散逻辑。

我该如何完成?到目前为止,这就是我所拥有的,axios.all(promises)并不等待前面的2个异步承诺。

fetchData = () => {
    let promises = [];

    axios.get("/api1.json")
        .then((response) => {
          //do logic 1
        })
        .then( () => { 

            promises.push(
                () => { return
                    //data for components
                    axios.get("/api21.json")
                        .then(response => { //do logic 2.1 }) 
                }   
            )           
            ,
            promises.push(
                () => { return
                    axios.get("/api22.json")
                        .then(response => { //do logic 2.2 })
                }
            )

        })

        axios.all(promises).then( //do final logic 3 after logic 2.1 and 2.2 have performed ))
    }

2 个答案:

答案 0 :(得分:3)

您可以执行第一个请求,然后使用Promise.all等待最后两个promise解析,然后再对这三个响应进行任何操作。

示例

fetchData = () => {
  axios.get("/api1.json").then(response1 => {
    Promise.all([axios.get("/api21.json"), axios.get("/api22.json")]).then(
      ([response2, response3]) => {
        console.log(response1, response2, response3);
      }
    );
  });
};

答案 1 :(得分:2)

探测器的原因是您试图运行axios诺言要快,而且axios.get在功能中太深了。你能试试这个吗?

fetchData = () => {

axios.get("/api1.json")
    .then((response) => {
      //do logic 1
    })
    .then( () => { 
        return axios.all([
            //data for components
            axios.get("/api21.json")
                .then(response => { //do logic 2.1 }),       
            axios.get("/api22.json")
                .then(response => { //do logic 2.2 })
        ]);
    })
    .then( // do final logic 3);
}