Dealing with asynchronicity using promises
In a real undo/redo plugin you will probably send data to a server, which is an asynchronous operation. We understood that asynchronicity must be dealt with inside Vuex actions. When you dispatch an action, store.dispatch('anAction')
, the dispatch
method returns a Promise
. In the following pages I will explain how you can handle asynchronous operations using Promise
, a relatively new JavaScript feature.
Dealing with asynchronous operations in JavaScript can be tricky. I have seen incredibly messy pieces of code just because the programmer didn't know how to deal with asynchronous code.
The worst way of waiting for a piece of data that will be available later is polling. Never do something like this:
// Just don't use this way! let dataFromServer; // ... const waitForData = () => { if(dataFromServer !== undefined) { doSomethingWith(dataFromServer); } else { setTimeout(waitForData, 100); } }; setTimeout(waitForData, 100...