Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在循环中使用Fetch查询?_Javascript_Reactjs - Fatal编程技术网

Javascript 如何在循环中使用Fetch查询?

Javascript 如何在循环中使用Fetch查询?,javascript,reactjs,Javascript,Reactjs,我通过一个带有不同URL的映射向服务器发出请求,然后将数据设置为状态并将其用于输出。我希望请求是连续的,但有时它们不能正常工作并出现错误,如何编写用于正常数据检索的代码 const urlList = ["countries", "states", "cities", "users"]; componentDidMount() { urlList.map( (url, index) => { return servicesAPI.getResour

我通过一个带有不同URL的映射向服务器发出请求,然后将数据设置为状态并将其用于输出。我希望请求是连续的,但有时它们不能正常工作并出现错误,如何编写用于正常数据检索的代码

const urlList = ["countries", "states", "cities", "users"];
componentDidMount() {
         urlList.map( (url, index) => {
            return servicesAPI.getResourse(url).then( (body) => {
                index !== 3 ?  this.setState({
                                 dataAPI : [...this.state.dataAPI, body] }) :
                                this.setState({
                                    dataAPI : [...this.state.dataAPI, body],
                                    loaded: true
                                })

            })
        })
export default  class ServicesAPI {
    _apiBase = `http://localhost:3001/`;


    async getResourse(url) {
        const res = await fetch(`${this._apiBase}${url}`);

        if (!res.ok) {
            throw new Error(`Could not fetch ${url}` +
                `, received ${res.status}`)
        }
        return await res.json();
    }
使用
Promise.all()

示例:


在可能的情况下,也可以使用async/await来获得更干净的代码。

在getResource func中有两个await关键字。它应该只有一个。不确定为什么要使用map在数组上循环,因为您没有使用它映射任何内容。使用promises<代码>风险值承诺=[];forEach(函数(元素){promises.push(yourRequest);});Promise.all(promises).then(results=>{…})“我希望请求是连续的”-您的代码将并行运行它们。我感谢您的精彩表演。请求是连续的,保持其顺序。
componentDidMount() {
     const fetchPromises = [];
     urlList.forEach( (url, index) => {
        fetchPromises.push(servicesAPI.getResourse(url));
     });

     const allResourcesPromise = Promise.all(fetchPromises);
     allResourcesPromise.then(data => {
        // list with responses
     }).catch(err => {
        console.log(err.toString());
     });

}