[Vuejs]-How to ensure that function passed as prop to Vue component is async?

2👍

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()

2👍

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.

👤Naren

1👍

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.

👤kissu

Leave a comment