起因, 目的:
补补 js 基础。
例1, 请求天气 api, 天气数据api
js 中的 await
- await 关键字只能在 async 函数内部使用。
- 函数内部可以使用 await,但是在函数外部直接使用 await 是不允许的。
async function fetchWeatherData(param) {
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?q=${param}&appid=e34b4c51d8c2b7bf48d5217fe52ff79e`
);
const data = await response.json();
if (data) {
// console.log("data: ", data);
// 解析数据,可以直接在函数内部进行解析.
countryName = data?.sys?.country;
console.log("函数内部: 国家名称是: ", countryName);
return data; // 返回数据. 用于在此函数外面进行处理.
}
} catch (e) {
console.log("error: ", e);
}
}
// 调用函数.
fetchWeatherData("London");
// 调用函数的第二种写法
fetchWeatherData("London").then((someCity) => {
console.log("函数外部: 国家名称是: ", someCity.sys.country);
});
/*
api 返回的结果是:
data: {
coord: { lon: -0.1257, lat: 51.5085 },
weather: [
{
id: 804,
main: 'Clouds',
description: 'overcast clouds',
icon: '04d'
}
],
base: 'stations',
main: {
temp: 287.13,
feels_like: 286.88,
temp_min: 286.05,
temp_max: 288.01,
pressure: 1009,
humidity: 88,
sea_level: 1009,
grnd_level: 1006
},
visibility: 10000,
wind: { speed: 5.14, deg: 290 },
clouds: { all: 100 },
dt: 1725867798,
sys: {
type: 2,
id: 2075535,
country: 'GB',
sunrise: 1725859588,
sunset: 1725906561
},
timezone: 3600,
id: 2643743,
name: 'London',
cod: 200
}
*/
例2, 获取 nasa api, 每日太空壁纸
async function fetchAPIData() {
const NASA_KEY = "RTM35gv1qOoqUTFMK1Gg0CtyELMQ8BvedQYkjQUY";
// const NASA_KEY = import.meta.env.VITE_NASA_API_KEY;
const url = "https://api.nasa.gov/planetary/apod" + `?api_key=${NASA_KEY}`;
// 先检查本地数据。
const today = new Date().toDateString();
const localKey = `NASA-${today}`;
try {
const data = await fetch(url);
const apiData = await data.json();
console.log(apiData);
const imgUrl = apiData.hdurl;
console.log("今日太空壁纸, 图片地址: ", imgUrl);
console.log("获取数据成功!");
} catch (err) {
console.log("获取数据失败!");
console.log(err.message);
}
}
// 调用函数
fetchAPIData();
/*
输出:
{
date: '2024-09-09',
explanation: "If you could fly over Mars, what might you see? The featured image shows exactly this in the form of a Mars Express vista captured over a particularly interesting region on Mars in July. The picture's most famous feature is Olympus Mons, the largest volcano in the Solar System, visible on the upper right. Another large Martian volcano is visible on the right horizon: Pavonis Mons. Several circular impact craters can be seen on the surface of the aptly named red planet. Impressively, this image was timed to capture the dark and doomed Martian moon Phobos, visible just left of center. The surface feature on the lower left, known as Orcus Patera, is unusual for its large size and oblong shape, and mysterious because the processes that created it still remain unknown. ESA's robotic Mars Express spacecraft was launched in 2003 and, among many notable science discoveries, bolstered evidence that Mars was once home to large bodies of water.",
hdurl: 'https://apod.nasa.gov/apod/image/2409/MarsPan_ExpressLuck_2048.jpg',
media_type: 'image',
service_version: 'v1',
title: 'Mars: Moon, Craters, and Volcanos',
url: 'https://apod.nasa.gov/apod/image/2409/MarsPan_ExpressLuck_1080.jpg'
}
今日太空壁纸, 图片地址: https://apod.nasa.gov/apod/image/2409/MarsPan_ExpressLuck_2048.jpg
获取数据成功!
*/
比如今天的太空图片是: