clod986
clod986

Reputation: 2647

How can I prevent calling the API multiple times?

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

Answers (1)

anish bhanwala
anish bhanwala

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

Related Questions