Home > Software design >  How to ensure that function passed as prop to Vue component is async?
How to ensure that function passed as prop to Vue component is async?

Time:11-13

Is it possible to check if a prop Function is async or not?

For example, here is a prop in my component:

      callbackFunction: {
        type: Function,
        default: null,
      },

How can I validate this and make sure that the passed in Function is declared as async?

CodePudding user response:

Yes, you can do with props "validator"

     callbackFunction: {
        type: Function,
        validator(value) {
          if (value?.constructor?.name === 'AsyncFunction') {
             return true;
          } else {
            console.error('Function should be async');
            return false;
          }
        },
        default() {},
      },

Here's the example.

Note: This does not break anything, If a requirement is not met, Vue will warn you in the browser's JavaScript console.

CodePudding user response:

Props cannot be async, they can only be sync. So no, no such validation is possible.


Here is a detailed page on all the types available: https://vuejs.org/api/options-state.html#props

Btw, passing functions is an anti-pattern in Vue (it's not React).
That blog post could give you more insight as of how to achieve something clean in Vue.

CodePudding user response:

There's no reliable way and no reason to do this. It could be regular function that returns a promise with exactly the same result, and it would be impossible to detect if it's asynchronous without calling it.

There may be no reason to restrict a callback to be asynchronous. A safe way that works with any kind of result is:

if (this.callbackFunction) 
  await this.callbackFunction()
  • Related