Created
July 19, 2017 04:03
-
-
Save ericls/f11d58b69faa236883fc5c0249b315dc to your computer and use it in GitHub Desktop.
async/await with fetch and map
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Use hacker news API as example | |
async function getData() { | |
const ids = await (await fetch('https://hacker-news.firebaseio.com/v0/topstories.json')).json() | |
const data = Promise.all( | |
ids.map(async (i) => await (await fetch(`https://hacker-news.firebaseio.com/v0/item/${i}.json?print=pretty`)).json()) | |
) | |
return data | |
} | |
getData() | |
.then(data => { | |
console.log(data) | |
}) | |
// Async/await is just a different way of writing promises. | |
// Even though it looks like synchronous code, don't think it that way. | |
// It ain't what you don't know that gets you into trouble. It's what you know for sure that just ain't so. | |
// It ain't asynchrony that gets you into trouble. It's what you think is synchronous that just ain't so. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you, this worked perfectly for what I needed. Was struggling to get my array from saying "undefined" upon importing into my app.js file using Express and 'FS'. I obviously need work in the async/await Promises area :)