Make sure to create an API key and add it in the .js file.
Last active
June 29, 2017 19:12
-
-
Save ConnerAiken/2bea1f177a5b4cbf12e7159ced28c0ed to your computer and use it in GitHub Desktop.
ES6: Promise Chain and Fetch API
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
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<title>ES6: Promises and Fetch API Example</title> | |
<meta charset="utf-8"> | |
<meta author="Conner Aiken"> | |
<meta content="width=device-width, initial-scale=1" name="viewport"> | |
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="row"> | |
<div class="col-md-12"> | |
<h4>ES6 Promise Chain Ex.</h4> | |
<p>Results are outputted to the console.</p><button id="startBtn">Start Promise Chain</button> | |
</div> | |
</div> | |
</div> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> | |
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> | |
<script src="./promise-fetch.js"></script> | |
</body> | |
</html> |
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
// ================================ | |
// Define dark-sky api class | |
// - Get key @ https://darksky.net | |
// ===================== | |
class darkSky { | |
constructor(apiKey, location = null) { | |
this.apiKey = apiKey, | |
this.baseUrl = 'https://api.darksky.net', | |
this.location = { | |
lat: location.lat ? location.lat : '37.8267', | |
long: location.long ? location.long : '-122.4233' | |
}, | |
this.endpoints = { | |
forecast: `${this.baseUrl}/forecast/${this.apiKey}/${this.location.lat},${this.location.long}` | |
} | |
}; | |
}; | |
// ================================ | |
// Define vars | |
// ===================== | |
const chainLog = $('#promiseChainLog'); | |
const startBtn = $('#startBtn'); | |
const corsProxy = 'https://cors-anywhere.herokuapp.com/'; | |
const darkSkyObj = new darkSky('yourAPIKey', { | |
lat: '47.6062', | |
long: '122.3321' | |
}); | |
// ================================ | |
// Define promises | |
// ===================== | |
const repackageForecastPromise = (jsonResult) => { | |
console.log("[repackageForecastPromise] called with parameter: ", jsonResult); | |
return new Promise((resolve, reject) => { | |
if (!jsonResult) | |
reject(jsonResult); | |
console.log(jsonResult); | |
resolve({ | |
"timezone": jsonResult.timezone, | |
"currently": jsonResult.currently, | |
"thisWeek": jsonResult.daily.data | |
}); | |
}); | |
}; | |
const showExecOrder = (param) => { | |
return new Promise((resolve, reject) => { | |
console.log("[showExecOrder] called with parameter: ", param); | |
resolve(param); | |
}); | |
} | |
const displayInDOM = (param, domElement, afterRepackage) => { | |
return new Promise((resolve, reject) => { | |
const jsonHint = afterRepackage ? 'Raw' : 'Repackaged'; | |
console.log("[displayInDOM] called with parameter: ", param, " and dom element ", domElement); | |
domElement.text('Restart Promise Chain'); | |
domElement.after(`<h4>JSON Output <small>(${jsonHint})</small></h4><pre>${JSON.stringify(param, undefined, 2)}</pre>`); | |
resolve(param); | |
}); | |
} | |
const deleteOldLogs = () => { | |
var elements = document.getElementsByTagName('pre') | |
while (elements[0]) { | |
elements[0].parentNode.removeChild(elements[0]) | |
} | |
console.log("\n\n---- Starting Promise Chain ------ \n\n"); | |
}; | |
// ================================ | |
// Handle btn click event | |
// ===================== | |
startBtn.on('click', () => { | |
deleteOldLogs(); | |
fetch(corsProxy + darkSkyObj.endpoints.forecast) | |
.then((response) => { | |
return response.json(); | |
}) | |
.then(data => displayInDOM(data, startBtn, false)) | |
.then(repackageForecastPromise) | |
.then(data => displayInDOM(data, startBtn, true)) | |
.then(showExecOrder) // identical to .then(repackagedObj => showExecOrder(repackagedObj)) | |
.then(showExecOrder('executed first')) | |
.then((res) => { | |
console.info("\n\nPromise chain has been completed.", res); | |
}) | |
.catch((error) => { | |
alert("An error occured!"); | |
console.error("An error occured in the promise chain", error); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment