Reputation: 2647
I have the following function
$(window).localDatabase('schooldata', schoolId)
which either returns a stored value or, if outdated, calls the following
return new Promise(function(resolve, reject){
console.log('Downloading school database');
axios.get('/api/school-database/'+schoolId+'/schooldata')
.then(response => {
$(window).storage(
'planner',
'save',
'schooldata-'+schoolId,
[response.data]
).then(function(response2){
resolve(response.data);
saveLastUpdate('schooldata-'+schoolId).then(function(response2){
triggerOnVueBus('db-updated:schooldata');
});
});
});
});
The code works flawlessly, except I have many Vue components that require the database and on startup call multiple times the Promise i pasted.
I would like to implement a method which does not make another request if one is pending already: what logic should I follow?
Upvotes: 0
Views: 2675
Reputation: 28
I think this should work. Create promise once and always return the same promise. If a promise is already resolved, the .then block is triggered immediately with already resolved value. Something like this:
if (!this.promise) {
this.promise = new Promise(function(resolve, reject) {
console.log('Downloading school database');
axios.get('/api/school-database/' + schoolId + '/schooldata')
.then(response => {
$(window).storage(
'planner',
'save',
'schooldata-' + schoolId, [response.data]
).then(function(response2) {
resolve(response.data);
saveLastUpdate('schooldata-' + schoolId).then(function(response2) {
triggerOnVueBus('db-updated:schooldata');
});
});
});
});
}
return this.promise;
Upvotes: 1