Skip to content

Instantly share code, notes, and snippets.

@junibrosas
Last active June 3, 2020 06:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save junibrosas/5a50dc40349a127a6206f2b1c0668531 to your computer and use it in GitHub Desktop.
Save junibrosas/5a50dc40349a127a6206f2b1c0668531 to your computer and use it in GitHub Desktop.
Async Await
let characterResponse = await fetch('http://swapi.co/api/people/2/')
let characterResponseJson = await characterResponse.json()
let films = await Promise.all(
characterResponseJson.films.map(async filmUrl => {
let filmResponse = await fetch(filmUrl)
return filmResponse.json()
})
)
console.log(films)
// the goodies
const callMethod = (methodName, ...params) => obj => obj[methodName](...params)
const awaitAll = promiseArray => Promise.all(promiseArray)
const prop = propName => obj => obj[propName]
const map = func => arr => arr.map(func)
const pipe = (...functions) => functions.reduce((compound, func) => (input => func(compound(input))))
const download = url => fetch(url).then(callMethod("json"))
// the code
download(
"http://swapi.co/api/people/2/"
)
.then(
pipe(
prop("films"),
map(download),
awaitAll,
)
)
.then(
console.log
)
.catch(
console.error
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment