20分钟带你掌握JS Promise和Async/Await( 三 )

示例3:从Web API中获取国家信息一般当从API中获取数据时,开发人员会精彩使用Promises 。如果在新窗口打开
https://restcountries.eu/rest/v2/alpha/cn,你会看到JSON格式的国家数据 。
通过使用Fetch API,我们可以很轻松的获得数据,以下是代码:
const fetchData = https://www.isolves.com/it/cxkf/yy/js/2021-03-31/async () => {const res = await fetch("https://restcountries.eu/rest/v2/alpha/cn"); // fetch() returns a promise, so we need to wait for itconst country = await res.json(); // res is now only an HTTP response, so we need to call res.json()console.log(country); // China's data will be logged to the dev console};fetchData();现在我们获得了所需的国家/地区数据,让我们转到最后一项任务 。
示例4:从Web API中获取一个国家的周边国家列表下面的fetchCountry函数从示例3中的api获得国家信息,其中的参数alpha3Code 是代指该国家的国家代码,以下是代码
// Task 4: 获得中国周边的邻国信息
const fetchCountry = async (alpha3Code) => {try {const res = await fetch(`https://restcountries.eu/rest/v2/alpha/${alpha3Code}`);const data = https://www.isolves.com/it/cxkf/yy/js/2021-03-31/await res.json();return data;} catch (error) {console.log(error);}};下面让我们创建一个fetchCountryAndNeighbors函数,通过传递cn作为alpha3code来获取中国的信息 。
const fetchCountryAndNeighbors = async () => {const china= await fetchCountry("cn");console.log(china);};fetchCountryAndNeighbors();在控制台中,我们看看对象内容:

20分钟带你掌握JS Promise和Async/Await

文章插图
 
在对象中,有一个border属性,它是中国周边邻国的alpha3codes列表 。
现在,如果我们尝试通过以下方式获取邻国信息 。
const neighbors =china.borders.map((border) => fetchCountry(border));neighbors是一个Promise对象的数组 。
当处理一个数组的Promise时,我们需要使用Promise.all 。
const fetchCountryAndNeigbors = async () => {const china = await fetchCountry("cn");const neighbors = await Promise.all(china.borders.map((border) => fetchCountry(border)));console.log(neighbors);};fetchCountryAndNeigbors();在控制台中,我们应该能够看到国家/地区对象列表 。
20分钟带你掌握JS Promise和Async/Await

文章插图
 
以下是示例4的所有代码,供您参考:
const fetchCountry = async (alpha3Code) => {try {const res = await fetch(`https://restcountries.eu/rest/v2/alpha/${alpha3Code}`);const data = https://www.isolves.com/it/cxkf/yy/js/2021-03-31/await res.json();return data;} catch (error) {console.log(error);}};const fetchCountryAndNeigbors = async () => {const china = await fetchCountry("cn");const neighbors = await Promise.all(china.borders.map((border) => fetchCountry(border)));console.log(neighbors);};fetchCountryAndNeigbors();总结完成这4个示例后,你可以看到Promise在处理异步操作或不是同时发生的事情时很有用 。相信在不断的实践中,对它的理解会越深、越强,希望这篇文章能对大家理解Promise和Async/Await带来一些帮助 。
这是本文中使用的代码:Asdkjbasrksbr 。




推荐阅读