Suppose I make an asynchronous request when the component loads. The component also has a submit button that the user can press to trigger a function that depends on the result of the original request. How can I delay the execution of a triggered function until the async request completes?
If this doesn't make sense, let me give you an example. MyComponent
Makes an asynchronous request getRandomColor()
on mounted
. The template of MyComponent
has <button @click="handleClick">
. handleClick
Call some functions saveColor()
. How do I ensure that saveColor()
is not called before the async getRandomColor()
completes?
I'm currently using Vue.js, but I think this question applies to all javascript.
You can achieve this by adding the
:disabled
attribute to the button element. The value of:disabled
will be based on the response. That is, if there is a response, enable it, otherwise disable it.Working Demonstration: