Javascript 如何并行执行两个异步函数,然后等待它们完成?

Javascript 如何并行执行两个异步函数,然后等待它们完成?,javascript,reactjs,Javascript,Reactjs,我试图从两个不同的API中获取数据,并希望并行执行,但我希望等待它们执行,然后继续执行下一行代码 componentDidMount() { this._isMounted = true; this.fetch1() // <-- Async method this.fetch2() // <-- Async method this.func(); // The above two lines of code needs to be done to e

我试图从两个不同的API中获取数据,并希望并行执行,但我希望等待它们执行,然后继续执行下一行代码

componentDidMount() {
    this._isMounted = true;
    this.fetch1() // <-- Async method
    this.fetch2() // <-- Async method
    this.func(); // The above two lines of code needs to be done to execute this line

  }

  async fetch1() {
    fetch("/api/abc123")
      .then(res => res.json())
      .then(res => {
          this.setState({ foo: res });
      });
  }

  async fetch2() {
    fetch("/api/def456")
      .then(res => res.json())
      .then(res => {
          this.setState({ bar: res });
      });
  }

func() {
    // Do something with the data from the APIs
  }
componentDidMount(){
这个。_isMounted=true;
this.fetch1()//{
this.setState({foo:res});
});
}
异步fetch2(){
获取(“/api/def456”)
.then(res=>res.json())
。然后(res=>{
this.setState({bar:res});
});
}
func(){
//对API中的数据执行一些操作
}
我使用,它有
axios.all()

执行多个并发请求 (链接中的代码)


只有在所有请求完成后才会解析,然后按照传递的顺序以
响应
数组的形式传递。

还可能重复在componentDidMount上使用async,然后在回迁时使用Wait。const fetchOne=等待fetch1();也有可能
function getUserAccount() {   
     return axios.get('/user/12345'); 
}

function getUserPermissions() {   
    return axios.get('/user/12345/permissions'); 
}

axios.all([getUserAccount(), getUserPermissions()])  
.then(axios.spread(function (acct, perms) {
    // Both requests are now complete   
}));
const promises = []
for(let request of requests){ promises.push(request) }

Promise.all(promises).then(res => /*res[0], res[1]*/)