Instead of simply copying example code from tutorials, I am challenging myself to grasp ES6 Promises by implementing them in a meaningful way within a real project.
Below is the frontend Vue.js/axios code I created that effectively utilizes Promises to populate five sections of the screen with data. In my backend loadData
action, I intentionally insert a one-second delay so I can observe each section loading sequentially:
<div id="app" class="pageContent">
<div>Data 1: {{data1}}</div>
<div>Data 2: {{data2}}</div>
<div>Data 3: {{data3}}</div>
<div>Data 4: {{data4}}</div>
<div>Data 5: {{data5}}</div>
</div>
<script>
const app = new Vue({
el: '#app',
data: {
data1: 'loading...',
data2: 'loading...',
data3: 'loading...',
data4: 'loading...',
data5: 'loading...'
},
methods: {
initialize: function () {
const that = this;
this.loadData('data1')
.then(() => {
return that.loadData('data2');
})
.then(() => {
return that.loadData('data3');
})
.then(() => {
return that.loadData('data4');
})
.then(() => {
return that.loadData('data5');
});
},
loadData: function (idCode) {
return new Promise((resolve, reject) => {
const that = this;
axios({
method: 'post',
url: 'controllerShowcaseLoadDataWithPromises',
data: {
action: 'loadData',
idCode: idCode
}
}).then(function (responseObject) {
const response = qsys.getResponse(responseObject);
that[idCode] = response.data.message;
setTimeout(resolve); // This line is crucial for proper execution
});
});
},
}
});
app.initialize();
Although the code functions as expected, I am puzzled about the necessity of using setTimeout(resolve)
. Could someone shed light on why this is needed and provide insight into a cleaner, more standard approach to achieve the same result?