ES2015 Promises and ES2017 Async/Await
const fetch = require("isomorphic-fetch");
function fetchAsPromise() {
fetch("https://itunes.apple.com/search?term=Doctor%20Who&media=music&entity=album")
.then(r => {
if (r.ok) {
return r.json();
} else {
throw new Error("Couldn't obtain information from the service");
}
}).then(json => json.results.map(result => {
console.log(result.collectionName);
})).catch(err => console.error(err.message));
console.log("Fetching!");
}
async function searchItunes(forTerm) {
const response = await fetch(`https://itunes.apple.com/search?term=${forTerm}&media=music&entity=album`);
if (response.ok) {
const json = await response.json();
return json.results.map(result => result.collectionName);
}
throw new Error("Could not retrieve results from service");
}
async function searchForDoctorWho() {
try {
let albums = await searchItunes("Doctor%20Who");
for (let album of albums) {
console.log(album);
}
} catch (err) {
console.error(`Failed to retrieve results: ${err.message}`);
}
}
async function fetchAsAsync() {
searchForDoctorWho();
console.log("Fetching!");
}
// async results don't output well in this playground when run in parallel, so... comment out the one you don't want to run.
//fetchAsPromise();
fetchAsAsync();
no comments