逻辑是这样的:
电话号码 =》获取所在城市名称 =》 获取城市代码 =》 获取城市天气
下一次的请求都会用到上次请求的结果
我试了下面的两种写法,感觉都很啰嗦,有没有什么好的写法呢?
// 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);
});
};
你的写法已经算是最好的写法了,目前
async
已经算是处理回调地狱最好的方式了