forked from stackp/promisejs
-
Notifications
You must be signed in to change notification settings - Fork 2
/
promise.min.js
6 lines (6 loc) · 2.35 KB
/
promise.min.js
1
2
3
4
5
6
/*
* Copyright 2012-2013 (c) Pierre Duquesne <[email protected]>
* Licensed under the New BSD License.
* https://github.com/stackp/promisejs
*/
(function(e){function t(){this._callbacks=[]}function n(e){function o(e){return function(){i+=1,r[e]=Array.prototype.slice.call(arguments),i===s&&n.done(r)}}var n=new t,r=[];if(!e||!e.length)return n.done(r),n;var i=0,s=e.length;for(var u=0;u<s;u++)e[u].then(o(u));return n}function r(e,n){var i=new t;return e.length===0?i.done.apply(i,n):e[0].apply(null,n).then(function(){e.splice(0,1),r(e,arguments).then(function(){i.done.apply(i,arguments)})}),i}function i(e){var t="";if(typeof e=="string")t=e;else{var n=encodeURIComponent,r=[];for(var i in e)e.hasOwnProperty(i)&&r.push(n(i)+"="+n(e[i]));t=r.join("&")}return t}function s(){var e;if(window.XMLHttpRequest)e=new XMLHttpRequest;else if(window.ActiveXObject)try{e=new ActiveXObject("Msxml2.XMLHTTP")}catch(t){e=new ActiveXObject("Microsoft.XMLHTTP")}return e}function o(e,n,r,o,u){function v(){l.abort(),f.done(a.ETIMEOUT,"",l)}var f=new t,l,c;r=r||{},o=o||{},u=u||{};try{l=s()}catch(h){return f.done(a.ENOXHR,""),f}c=i(r),e==="GET"&&c&&(n+="?"+c,c=null),l.open(e,n),l.setRequestHeader("Content-type","application/x-www-form-urlencoded");for(var p in o)o.hasOwnProperty(p)&&l.setRequestHeader(p,o[p]);for(var d in u)d!=="beforeSend"&&u.hasOwnProperty(d)&&(l[d]=u[d]);var m=a.ajaxTimeout;if(m)var g=setTimeout(v,m);return l.onreadystatechange=function(){m&&clearTimeout(g);if(l.readyState===4){var e=!l.status||(l.status<200||l.status>=300)&&l.status!==304,t=l.responseText;if((l.getResponseHeader("Content-Type")||"").indexOf("json")>-1)try{t=JSON.parse(t)}catch(n){e=a.EDECODEJSON}f.done(e,t,l)}},u.beforeSend&&u.beforeSend(l),l.send(c),f}function u(e){return function(t,n,r,i){return o(e,t,n,r,i)}}t.prototype.then=function(e,n){var r;return this._isdone?r=e.apply(n,this.result):(r=new t,this._callbacks.push(function(){var t=e.apply(n,arguments);t&&typeof t.then=="function"&&t.then(r.done,r)})),r},t.prototype.done=function(){this.result=arguments,this._isdone=!0;for(var e=0;e<this._callbacks.length;e++)this._callbacks[e].apply(null,arguments);this._callbacks=[]};var a={Promise:t,join:n,chain:r,ajax:o,get:u("GET"),post:u("POST"),put:u("PUT"),del:u("DELETE"),ENOXHR:1,ETIMEOUT:2,EDECODEJSON:3,ajaxTimeout:0};typeof define=="function"&&define.amd?define(function(){return a}):e.promise=a})(this)