Created
January 17, 2017 05:47
-
-
Save jbruni/e89a229cd1b63a5049eb82bc10e67324 to your computer and use it in GitHub Desktop.
Resolve/Reject Promises externally
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
let contexts = {} | |
function getContext(key) { | |
if (typeof contexts[key] === 'undefined') { | |
contexts[key] = { promise: null, resolve: null, reject: null } | |
} | |
return contexts[key] | |
} | |
function getPromise(key) { | |
let context = getContext(key) | |
if (context.promise === null) { | |
context.promise = new Promise((resolve, reject) => { | |
context.resolve = resolve | |
context.reject = reject | |
}) | |
} | |
return context.promise | |
} | |
function resolvePromise(key, value) { | |
sealPromise(key, true, value) | |
} | |
function rejectPromise(key, error) { | |
sealPromise(key, false, error) | |
} | |
function sealPromise(key, resolve_or_reject, result) { | |
let context = getContext(key) | |
if (context.promise !== null) { | |
if (resolve_or_reject) { | |
context.resolve(result) | |
} else { | |
context.reject(result) | |
} | |
context.promise = null | |
context.resolve = null | |
context.reject = null | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sample usage:
A few words about the context here: after a Modal for login is shown, the actual login may happen or fail by many different reasons, in many different ways... there is traditional user/pass, there is social login (oAuth - in distinct window), there is the sign up form... it is only when the modal is closed (be it by user hitting close button, or any other way) that the actual login state is consulted, providing the resolved/rejected state for the component which triggered the Modal display.