ES6之promise天气案例

<p>
			<span class="add"></span>
			<span class='weather'></span>
			<span class='temp'></span>
			<img src="" class="img" width="30">
		</p>
		<script>
			$(function(){
				// 获取网络请求 信息 (根据不同的url返回不同的结果)
				function getApi(url){
					//返回一个承诺
					return new Promise((resolve,reject)=>{
						$.ajax({
							url:url,
							dataType:"jsonp",
							success:function(res){
								resolve(res);
							},
							error:function(err){
								reject(err)
							}
						})
					})
				}
				//获取地址
				var urlA = "https://apis.map.qq.com/ws/location/v1/ip?key=CAABZ-AVSAQ-RDR5L-GTBDJ-HLA4O-A5FDB&output=jsonp&_=1593478015329";
				var urlB = "https://wis.qq.com/weather/common?weather_type=observe|forecast_24h|air&source=pc";
				//添加&province=省份&city=城市
				getApi(urlA)
				.then(add=>{//获取地址
					console.log(add);
					var info=add.result.ad_info;//具体的地址信息
					$('.add').text(info.city);
					
					return getApi(urlB+`&province=${info.province}&city=${info.city}`)
				})
				.then(data=>{//获取天气
					console.log(data);
					$('.weather').text(data.data.observe.weather);
					$('.temp').text(data.data.observe.degree)
					$('.img').attr("src",`https://mat1.gtimg.com/pingjs/ext2020/qqindex2018/dist/img/weather/${data.data.observe.weather_code}.svg`)
				})
				.catch(err=>{//失败
					console.error(err);
				})
			})

你可能感兴趣的:(javascript,es6,jquery)