如何在componentDidMount中调用两个asynch方法?

时间:2016-04-11 13:44:48

标签: javascript reactjs

我在我的App组件中有这两个方法,我想使用getLocation来设置纬度和经度,然后我想调用getWeather方法。这两种方法我想在componentDidMounth中调用

getLocation: function() {
  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(       
      function(position){
       this.setState({
         location: position
      });
    }.bind(this)
  );
 }
}

  getWeather: function() {
    let latitude =48.1568806; //just for test
    let longitude =17.0739704; //just for test
    $.ajax({
      url:`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&APPID=${this.state.key}`,
      dataType: 'json',
      async: true,
      cache: false,
      success: function(data){
        this.setState({weather: data})
      }.bind(this),
      error: function(e){
      console.log(e);
    }

    });
  },

但我需要等待getLocation。

我该如何处理?

1 个答案:

答案 0 :(得分:2)

如果您需要将位置传递给getWeather,则可以在getLocation()

的回调中执行此操作
componentDidMount: function() {
  this.getLocation();
}
getLocation: function() {
  if(navigator.geolocation){
    navigator.geolocation.getCurrentPosition(       
      function(position){
       this.setState({
         location: position
      });
      // Add call here, change getWeather to take a location object
      this.getWeather(location);

    }.bind(this)
  );
 }
}

更多的解耦解决方案是使用promises

componentDidMount: function() {
    this.getLocation().done(location=>{
      this.getWeather(location);
    });
},
getLocation: function() {
  return new Promise((resolve, reject)=>{
    if(navigator.geolocation){
      navigator.geolocation.getCurrentPosition(function(position){
        this.setState({location: position});
        resolve(location);    
      }.bind(this))
    } else {
      reject();
    }
  });
 }
}