如何在本机结束后执行另一个函数?

时间:2019-04-08 17:10:46

标签: react-native

我有一个查询,该查询具有对服务器做出响应的功能,因此需要一段时间,并且在尝试执行其他功能时会发生错误。由于该函数响应来自服务器的数组,而当其他函数请求该数组时,即使它没有。必须解决这个问题。例子:

responseServer(tarea) {
     return fetch(url)
      .then((response) => response.json())
      .then((responseJson) => {
        this.setState({ refresh: false })
        global.refresh = false
        let data = [];
        let Milestone = [];

        Object.values(responseJson.summary).forEach(item => {
          data = data.concat(item);
        });

        const result = ["Milestone"]
          .reduce((total, category) => ({
            ...total,
            [category]: data.filter(line => line.includes(category)) 
          }), {})

        Object.values(result.Milestone).forEach(item => {
          Milestone = Milestone.concat(item)
        });

        this.setState({
          Milestone: Milestone
        })
      })
}

和另一个功能

sacarPorcentaje(item) {
 this.responseServer(item)
 let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
      console.log(summaryCopy)
      var Okeys = 0;
      var total = 0;
      for (var i = 0; i < summaryCopy.length; i++){
        for(var j = 0; j < summaryCopy[i].length; j++){
          if(summaryCopy[i][j] === "OK") {
            Okeys = Okeys + 1
          }
        }
        total = total + 1 
      }
      console.log(Okeys)
      console.log(total)
}

2 个答案:

答案 0 :(得分:1)

您应该将sacarPorcentaje()更新为async功能。然后await函数调用将解决您的问题

async sacarPorcentaje (item) {
 await this.responseServer(item)
 let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
      console.log(summaryCopy)
      var Okeys = 0;
      var total = 0;
      for (var i = 0; i < summaryCopy.length; i++){
        for(var j = 0; j < summaryCopy[i].length; j++){
          if(summaryCopy[i][j] === "OK") {
            Okeys = Okeys + 1
          }
        }
        total = total + 1 
      }
      console.log(Okeys)
      console.log(total)
}

对于此问题,还有另一种解决方案。请在Promise中搜索如何使用JS

答案 1 :(得分:0)

我认为您在then函数中调用responseServer函数时需要使用sacarPorcentaje

sacarPorcentaje(item) {
 this.responseServer(item).then(() => {
 let summaryCopy = this.state.Milestone.map(data => {return data.split(",")})
      console.log(summaryCopy)
      var Okeys = 0;
      var total = 0;
      for (var i = 0; i < summaryCopy.length; i++){
        for(var j = 0; j < summaryCopy[i].length; j++){
          if(summaryCopy[i][j] === "OK") {
            Okeys = Okeys + 1
          }
        }
        total = total + 1 
      }
      console.log(Okeys)
      console.log(total)
   }
}