1//Here i have filmresponse.json() which will return promise so i uses promise.
2//all otherwise it won't be possible to run it
3
4let characterResponse = await fetch('http://swapi.co/api/people/2/')
5let characterResponseJson = await characterResponse.json()
6let films = await Promise.all(
7 characterResponseJson.films.map(async filmUrl => {
8 let filmResponse = await fetch(filmUrl)
9 return filmResponse.json()
10 })
11)
12console.log(films)
13
1// Function to fetch Github info of a user.
2const fetchGithubInfo = async (url) => {
3 console.log(`Fetching ${url}`)
4 const githubInfo = await axios(url) // API call to get user info from Github.
5 return {
6 name: githubInfo.data.name,
7 bio: githubInfo.data.bio,
8 repos: githubInfo.data.public_repos
9 }
10}
11
12// Iterates all users and returns their Github info.
13const fetchUserInfo = async (names) => {
14 const requests = names.map((name) => {
15 const url = `https://api.github.com/users/${name}`
16 return fetchGithubInfo(url) // Async function that fetches the user info.
17 .then((a) => {
18 return a // Returns the user info.
19 })
20 })
21 return Promise.all(requests) // Waiting for all the requests to get resolved.
22}
23
24
25fetchUserInfo(['sindresorhus', 'yyx990803', 'gaearon'])
26 .then(a => console.log(JSON.stringify(a)))
27
28/*
29Output:
30[{
31 "name": "Sindre Sorhus",
32 "bio": "Full-Time Open-Sourcerer ·· Maker ·· Into Swift and Node.js ",
33 "repos": 996
34}, {
35 "name": "Evan You",
36 "bio": "Creator of @vuejs, previously @meteor & @google",
37 "repos": 151
38}, {
39 "name": "Dan Abramov",
40 "bio": "Working on @reactjs. Co-author of Redux and Create React App. Building tools for humans.",
41 "repos": 232
42}]
43*/
44