A mechanism is required for users to submit multiple files through a Vue form component. Prior to sending the data to a remote JSON API endpoint, these files need to be processed.
An attempt was made to address this by utilizing FileReader and an asynchronous foreach loop in the following manner:
methods: {
readerLoaded(geojson, date, post_data) {
post_data.dated_profiles.push({
'date': date,
'geojson': geojson
});
},
setupReader(file, date, post_data, readerLoaded) {
var reader = new FileReader();
reader.onload = function(e) {
const result = JSON.parse(e.target.result);
// Send result to callback
readerLoaded(result, date, post_data);
};
reader.readAsText(file);
},
validate() {
if ( this.$refs.form.validate() ) {
/* Process GeoJSON files to POST data to API */
const data = {
'name': this.name,
'index': this.index,
'dated_profiles': Array()
}
const asyncLoopFunction = async (datasets, post_data, setupReader, readerLoaded) => {
const promises = datasets.map(function (item) { return setupReader(item.file, item.date, post_data, readerLoaded); })
return await Promise.all(promises)
}
asyncLoopFunction(this.datasets, data, this.setupReader, this.readerLoaded).then( () => {
console.log('All async tasks complete!')
console.log("After async", data)
this.$store.dispatch('postProfile', data)
});
}
}
The issue at hand involves passing the final JSON data object to a Vuex store action via dispatch
, where the dated_profiles
array ends up being empty.
- Upon inspecting the JSON object after completion of the async loop, the browser console shows this
. Although it appears empty, expanding it reveals the correct full array...Object { name: "foo", index: "1", dated_profiles: [] }
- When attempting to send this data with the request, it asserts that the array is indeed empty. Isn't it supposed to wait for all promises to finish?
The reason behind the failure of my async/await combination remains unclear. Could you help pinpoint where I may have gone wrong?