Skip to content

Instantly share code, notes, and snippets.

@romabelka
Last active August 29, 2015 14:16
Show Gist options
  • Save romabelka/f7c63af677bdfb5bf4dc to your computer and use it in GitHub Desktop.
Save romabelka/f7c63af677bdfb5bf4dc to your computer and use it in GitHub Desktop.
//---------Promise----------
var Promise = function() {
this.__successCallbacks = [];
this.__errorCallbacks = [];
this.__value = undefined;
this.__state = 'pending';
//state = pending, success, error
this.then = function(successHandler, errorHandler) {
this.done(successHandler);
this.fail(errorHandler);
return this
};
this.done = function(callback) {
if (callback && typeof callback === 'function') {
this.__successCallbacks.push(callback);
if (this.__status === 'success') {
callback.apply(this, this.__value)
}
}
return this
};
this.fail = function(callback) {
if (callback && typeof callback === 'function') {
this.__errorCallbacks.push(callback);
if (this.__status === 'error') {
callback.apply(this, this.__value)
}
}
return this
};
this.getState = function() {return this.__state};
this.__setState = function(args) {
if (this.__state !== 'pending') {return this}
this.__state = args.status;
this.__value = args.value;
this['__' + this.__state + 'Callbacks'].forEach(function(callback) {
callback.apply(this, this.__value)
}.bind(this));
console.log('---', this);
return this
}
};
//---------Deffered---------
var Deffered = function() {
var promise = new Promise();
this.resolve = function() {
promise.__setState({
status: 'success',
value: arguments
})
};
this.reject = function(err) {
promise.__setState({
status: 'error',
value: [err]
})
};
this.promise = function() {return promise}
};
//--------Ajax---------------
var Get = function (options) {
var xmlhttp, deffered = new Deffered();
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function (ev) {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
if (options.success != null && typeof options.success === 'function') {
options.success.call(this.response, this, ev);
}
deffered.resolve(this.response, this, ev)
} else {
if (options.error != null && typeof options.error === 'function') {
options.error.apply(this, arguments)
}
deffered.reject(new Error(xmlhttp.message || 'some trouble with ajax'))
}
}
};
xmlhttp.open("GET", options.url, true);
xmlhttp.send();
return deffered.promise()
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment