Skip to content

Instantly share code, notes, and snippets.

@greenido
Created October 21, 2014 19:52
Show Gist options
  • Save greenido/6536afe242f15c19749f to your computer and use it in GitHub Desktop.
Save greenido/6536afe242f15c19749f to your computer and use it in GitHub Desktop.
Promises Simple Example
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="description" content="Simple example on Promises">
<meta name="author" content="Ido Green | greenido.wordpress.com | @greenido">
</head>
<body>
<h2>Promises Simple Example</h2>
<div class="main-feed"></div>
<script>
(function() {
function getUrl(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
// 'http://pipes.yahoo.com/pipes/pipe.run?_id=b1503e8154a95936d28a1d5175017426&_render=json';
var newsEndPointUrl = 'feed.json';
getUrl(newsEndPointUrl).then(function(response) {
console.log("Success! We got the feed.", response);
var feed = JSON.parse(response);
var stories = feed.value.items;
var ul = "<ul>";
for (var i = 0; i < stories.length; i++) {
var title = stories[i].title;
//var desc = stories[i].description;
var link = stories[i].link;
ul += '<li><h3><a class="story" href="'+ link +'">' + title + '</a></h3> ';
//+ '<p>'+ desc +'</p> </li>';
};
ul += "</ul>";
var mainFeed = document.querySelector('.main-feed');
function addHtmlToPage(content) {
var div = document.createElement('div');
div.innerHTML = content;
mainFeed.appendChild(div);
}
addHtmlToPage(ul);
}, function(error) {
console.error("Failed! No feed for you", error);
});
})();
</script>
<hr>
<p>
For more on Promises: <a href="http://www.html5rocks.com/en/tutorials/es6/promises/">JavaScript Promises on html5rocks</a>
and <a href="http://www.html5rocks.com/en/tutorials/es6/promises/async-example.html">another example</a>
</p>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment