[Vuejs]-How can I wait until a variable is available?

0👍

Make publicGame async:

async publicGame()

use await on your this.$guard function:

const valid = await this.$guard('Moderate games')

Then use an if statement on valid:

if (valid) {
   //now it works.
}

You’re ignoring the promise on your code, but we’re using the async/await pattern here.

0👍

You have to handle you desired behaviour inside the $guard action response. You can add additional field options and execute them, for example

export default {
    Auth,
    install (Vue, options) {
        Vue.prototype.$guard = async function(permission, options){
           await axios.post('/permission',{permission: permission},{ headers: {
                'X-Requested-With': 'XMLHttpRequest',
                "X-CSRF-TOKEN": Auth.state.token
            }}).then(response=>{                
                if (options.on_success != undefined) {
                   options.on_success(response.data.access === 1);
                }
            }).catch(function (error) {
                if (options.on_error != undefined) {
                   options.on_error(error);
                }
            });
        }
    }
}

Then when you call the $guard function you define what to do on_success and on_error

publicGame()
{
                this.$guard('Moderate games', {
                  on_success: function(can) {
                    if(can){
                      console.log('can');
                    } else {
                      console.log('can not');
                    }
                  },
                  on_error: function(error) {
                    console.log("Error: ", error);
                  }
                })
}

Leave a comment