Skip to content

Commit

Permalink
Implemented Promises interface
Browse files Browse the repository at this point in the history
  • Loading branch information
pinceladasdaweb committed Sep 25, 2017
1 parent f7fa1f8 commit f5150b1
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 20 deletions.
4 changes: 2 additions & 2 deletions build/tweetlight.min.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 28 additions & 18 deletions src/tweetlight.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,27 +52,37 @@
counter = this.counter ? '&count=' + this.counter : '',
endpoint = this.endpoint + '?' + type + counter;

this.getJSON(endpoint, this.loadTweets.bind(this), this.failure.bind(this));
this.getJSON(endpoint).then(this.loadTweets.bind(this), this.failure.bind(this));
},
getJSON: function (path, success, fail) {
var xhttp = new XMLHttpRequest();

xhttp.open('GET', path, true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
if ((this.status >= 200 && this.status < 300) || this.status === 304) {
var response = JSON.parse(this.responseText);

success.call(this, response);
} else {
fail.call(this, this.status + ' - ' + this.statusText);
getJSON: function (path) {
return new Promise(function(resolve, reject) {
var xhttp = new XMLHttpRequest();

xhttp.open('GET', path, true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhttp.setRequestHeader('Content-type', 'application/json');
xhttp.onreadystatechange = function () {
if (this.readyState === 4) {
if ((this.status >= 200 && this.status < 300) || this.status === 304) {
var response = JSON.parse(this.responseText);

resolve(response);
} else {
var error = this.statusText;

reject('Http/App Error: ' + error);
}
}
}
};
xhttp.send();
xhttp = null;
xhttp.onerror = processError;
xhttp.onabort = processError;
xhttp.send();
xhttp = null;

function processError (err) {
reject('Network Error: ' + err.target.status);
}
});
},
loadTweets: function (tweets) {
var apiStatus = tweets.httpstatus;
Expand Down

0 comments on commit f5150b1

Please sign in to comment.