Last active
April 24, 2018 14:21
-
-
Save WebReflection/4b4a6ae543722873e88be37c38a8d75f to your computer and use it in GitHub Desktop.
Bringing addListeners and removeListeners to Promises.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (wm) {'use strict'; | |
// original proposal via Oliver Dunk @oliverdunk_ via ES ML | |
// (c) Andrea Giammarchi - (ISC) | |
Object.defineProperties( | |
Promise.prototype, | |
{ | |
addListeners: { | |
configurable: true, | |
value: function addListeners(resolve, reject) { | |
var once = wm.get(this); | |
if (!once) { | |
wm.set(this, once = this.then( | |
function (result) { | |
once.result = result; | |
each(result, once.resolve, once.reject); | |
}, | |
function (error) { | |
once.result = error; | |
each(error, once.reject, once.resolve); | |
} | |
)); | |
once.resolve = []; | |
once.reject = []; | |
} | |
if (once.hasOwnProperty('result')) { | |
this.then(resolve || Object, reject || Object); | |
} else { | |
if (resolve && once.resolve.indexOf(resolve) < 0) | |
once.resolve.push(resolve); | |
if (reject && once.reject.indexOf(reject) < 0) | |
once.reject.push(reject); | |
} | |
return this; | |
} | |
}, | |
removeListeners: { | |
configurable: true, | |
value: function removeListeners(resolve, reject) { | |
var i, once = wm.get(this); | |
if (once) { | |
if (resolve) { | |
i = once.resolve.indexOf(resolve); | |
if (-1 < i) once.resolve.splice(i, 1); | |
} | |
if (reject) { | |
i = once.reject.indexOf(reject); | |
if (-1 < i) once.reject.splice(i, 1); | |
} | |
} | |
return this; | |
} | |
} | |
} | |
); | |
function each(info, toInvoke, toClean) { | |
toClean.splice(0); | |
toInvoke.splice(0).forEach(invoke, info); | |
} | |
function invoke(fn) { | |
fn(this); | |
} | |
}(new WeakMap)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Test via:
or via
and fail via