互相依赖的异步请求, 应该怎么简写?

逻辑是这样的:
电话号码 =》获取所在城市名称 =》 获取城市代码 =》 获取城市天气

下一次的请求都会用到上次请求的结果

我试了下面的两种写法,感觉都很啰嗦,有没有什么好的写法呢?

// async
onFetchPosition = async () => {
    const { actions } = this.props;
    const data = await API.fetchPosition(this.state.number);
    const city = await API.fetchCityCode(data.data.result.province);
    const weather = await API.fetchWeather(city.data.code);
    actions.fetchPhonePosition(data.data.result);
    actions.fetchCityCode(city.data);
    actions.fetchWeatherInfo(weather.data.weatherinfo);
}
// promise
 onCheckPosition = () => {
    new Promise((resolve) => {
      API.fetchPosition(this.state.number, (position) => {
        this.props.actions.fetchPhonePosition(position);
        resolve();
      });
    }).then(() => {
      API.fetchCityCode(this.props.position.province, (city) => {
        this.props.actions.fetchCityCode(city);
        API.fetchWeather(this.props.position.code, (weather) => {
          this.props.actions.fetchWeatherInfo(weather);
        });
      });
    }).catch((error) => {
      throw new Error(error);
    });
  };
阅读 2.3k
2 个回答

你的写法已经算是最好的写法了,目前 async 已经算是处理回调地狱最好的方式了

不是回答的回答
为什么不让后端来做,直接把电话给后端,后端聚合电话号码所在的城市和天气一起返回给你。。。多简单

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题