Last active
February 22, 2019 15:16
-
-
Save dino-su/175f3bd3e0457081c992df8b765df91c to your computer and use it in GitHub Desktop.
async/await request example
This file contains hidden or 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
const fs = require('fs'); | |
const request = require('request'); | |
function fetch(url) { | |
return new Promise(function(resolve) { | |
request(url, function(error, response, body) { | |
resolve(JSON.parse(body)); | |
}); | |
}); | |
} | |
function fetchAll(urls) { | |
return Promise.all(urls.map(function(url) { | |
return fetch(url); | |
})); | |
} | |
function flatten(array) { | |
return array.reduce(function(prev, current) { | |
const images = current.message; | |
return prev.concat(images); | |
}, []); | |
} | |
function prettyify(json) { | |
return JSON.stringify(json, null, 2); | |
} | |
function writeFile(file, data) { | |
fs.writeFile(file, data, 'utf8', function() { | |
console.log('File Saved!'); | |
}); | |
} | |
async function main() { | |
var urls = [ | |
'https://dog.ceo/api/breed/akita/images/random/10', | |
'https://dog.ceo/api/breed/chow/images/random/10', | |
'https://dog.ceo/api/breed/dhole/images/random/10', | |
'https://dog.ceo/api/breed/dingo/images/random/10', | |
'https://dog.ceo/api/breed/eskimo/images/random/10' | |
]; | |
const json = await fetchAll(urls); | |
const flattenedJson = flatten(json); | |
writeFile('dogs.json', prettyify(flattenedJson, null, 2)); | |
} | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment