UNPKG

promise.rsvp

Version:

Promise events listen base native Promise

6 lines 2.14 kB
/*! * PromiseRsvp v1.0.0 * (c) 2014-2018 xuxihai * Released under the MIT License. */ !function(e,n){"object"==typeof exports&&"undefined"!=typeof module?module.exports=n():"function"==typeof define&&define.amd?define(n):e.PromiseRsvp=n()}(this,function(){"use strict";var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function i(e){var n=e._promiseCallbacks;return n||(n=e._promiseCallbacks={}),n}var t={instrument:!1};({mixin:function(e){return e.on=this.on,e.off=this.off,e.trigger=this.trigger,e._promiseCallbacks=void 0,e},on:function(e,n){if("function"!=typeof n)throw new TypeError("Callback must be a function");var t=i(this),r=t[e];r||(r=t[e]=[]),-1===r.indexOf(n)&&r.push(n)},off:function(e,n){var t=i(this);if(n){var r=t[e],o=r.indexOf(n);-1!==o&&r.splice(o,1)}else t[e]=[]},trigger:function(e,n,t){var r=i(this)[e];if(r)for(var o=0;o<r.length;o++)(0,r[o])(n,t)}}).mixin(t);var o=t,n=function(e,n){if(2!==arguments.length)return t[e];t[e]=n};o.configure=n;var f=[];var s=function(e,n,t,r){1===f.push({name:e,payload:{eventName:e,promise:n,result:t,error:r,stack:o["instrument-with-stack"]?new Error("promise->"+n.$id+" stack").stack:null}})&&setTimeout(function(){for(var e=0;e<f.length;e++){var n=f[e];o.trigger(n.name,n.payload)}f.length=0},0)},r=Promise,u=0;function a(e){if(!(this instanceof a))throw new TypeError("Cannot call a class as a function");u++;var o=new r(function(n,t){var r=function(e){setTimeout(function(){if(s("rejected",o,null,e),!0===o._hasDownstreams)return t(e);s("error",o,null,e)},0)};try{return e(function(e){return setTimeout(function(){s("fulfilled",o,e)}),n(e)},r)}catch(e){return r(e)}});return o.$id=u,o.__proto__=a.prototype,s("created",o),o}return a.__proto__=Promise,a.prototype.__proto__=Promise.prototype,a.prototype.then=function(e,n){return this._hasDownstreams=!0,r.prototype.then.call(this,e,n)},a.on=o.on.bind(o),a.off=o.off.bind(o),a.configure=o.configure,a.deferred=function(e){var t={resolve:void 0,reject:void 0};return t.promise=new e(function(e,n){t.resolve=e,t.reject=n}),t}.bind(e,a),a.setup=function(){e.Promise=a},a});