admin管理员组

文章数量:1410712

In a function I loop, in which I’m making fetch calls. When all calls are finished, I need to save the values in a variable, but that’s not being possible for me to be asynchronous to the calls.

getReportsGroup(bukrs){
        
    //TOTAL OF A PROJECT GROUP
    fetch('api/Reports/GetDataIRPA?SETCLASS=' + this.state.SETCLASS, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
       this.setState({
           reportIRPA: data
       });
     });
}

getTotalProjects(){
   //Browse selected projects
   for (var i = 0; i < this.state.selectProjects.length; i++) {
       this.getReportsGroup(this.state.selectProjects[i].bukrs);
   }
    
   console.log('finish all fetch');
}

The getTotalProjects function is performing a loop in which getReportsGroup is called (fetch is made here). At the end of all fetchs I need to display a message in getTotalProjects. Currently, being asynchronous, it performs the console.log('finish all fetch') before finishing all fetch.

In a function I loop, in which I’m making fetch calls. When all calls are finished, I need to save the values in a variable, but that’s not being possible for me to be asynchronous to the calls.

getReportsGroup(bukrs){
        
    //TOTAL OF A PROJECT GROUP
    fetch('api/Reports/GetDataIRPA?SETCLASS=' + this.state.SETCLASS, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
       this.setState({
           reportIRPA: data
       });
     });
}

getTotalProjects(){
   //Browse selected projects
   for (var i = 0; i < this.state.selectProjects.length; i++) {
       this.getReportsGroup(this.state.selectProjects[i].bukrs);
   }
    
   console.log('finish all fetch');
}

The getTotalProjects function is performing a loop in which getReportsGroup is called (fetch is made here). At the end of all fetchs I need to display a message in getTotalProjects. Currently, being asynchronous, it performs the console.log('finish all fetch') before finishing all fetch.

Share Improve this question edited Dec 5, 2021 at 7:48 Riccardo Raffini 3961 gold badge7 silver badges21 bronze badges asked Oct 14, 2019 at 8:51 RichardSCRichardSC 112 silver badges4 bronze badges 2
  • You need promise.all instead of looping all promises. developer.mozilla/en-US/docs/Web/JavaScript/Reference/…. If not understand let me know i will add code for this – Shubham Verma Commented Oct 14, 2019 at 8:55
  • You're saving the data from each fetch to the same state property, basically overriding the data from the previous fetch. That can't be what you want...? – Andy Commented Oct 14, 2019 at 9:03
Add a ment  | 

3 Answers 3

Reset to default 4

You can use another library

    const request = new XMLHttpRequest();
    request.open('GET', '/api/<your_api>', false);  // `false` makes the request synchronous
    request.send(null);
    if (request.status !== 200) {
      // handle an error here
      return
    }

    const data = JSON.parse(request.responseText);

You need to wait until promise resolved. Return promise in first method and apply .then in second

getReportsGroup(bukrs){

    //TOTAL OF A PROJECT GROUP
    return fetch('api/Reports/GetDataIRPA?SETCLASS=' + this.state.SETCLASS, {
        method: 'GET',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json',
        }
    })
    .then(response => response.json())
    .then(data => {
       this.setState({
           reportIRPA: data,
       });
     });
}

getTotalProjects(){
   //Browse selected projects
   var promises = []; //array of promises
   for (var i = 0; i < selectProjects.length; i++) {
       var promise = this.getReportsGroup(selectProjects[i].bukrs); //single promise
       promises.push(promise);
   }
   Promise.all(promises ).then(function() {
      console.log("DISPLAY your Message here"); // display here
  });
   console.log('finish all fetch');
}

You can convert your code into promises and use promises instead of direct Fetch calls. Covert each call into a promises and use promise.all() to execute them all together. Which will work when all the promises are resolved.

本文标签: javascriptSynchronous fetchReactJSStack Overflow