Skip to content

Instantly share code, notes, and snippets.

@jbruni
Created January 17, 2017 05:47
Show Gist options
  • Save jbruni/e89a229cd1b63a5049eb82bc10e67324 to your computer and use it in GitHub Desktop.
Save jbruni/e89a229cd1b63a5049eb82bc10e67324 to your computer and use it in GitHub Desktop.
Resolve/Reject Promises externally
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
}
}
@jbruni
Copy link
Author

jbruni commented Jan 17, 2017

Sample usage:

    userSignInShow ({ commit }) {
        commit('USER_SET_SHOW_SIGN_IN', true)
        return getPromise('userSignIn')
    },

    userSignInHide ({ commit, getters }) {
        commit('USER_SET_SHOW_SIGN_IN', false)
        if (getters.userLoggedIn) {
            resolvePromise('userSignIn', true)
        } else {
            rejectPromise('userSignIn', new Error('Not logged in'))
        }
    },

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment