0

I have declared 'service':

// myService.js
export default {
  someService: _.debounce(
    function  someService(rule, value, callback) {
      myApi.get(
        `check-input/${value}`,
      )
      .then((response) => {
        if (response.data.valid) {
          callback();
        } else {
          callback(new Error('Invalid value'));
        }
      })
      .catch(() => {
        callback(new Error('Internal error. Please try later.'));
      });
  },2000)};

I would like to use this service two times independently at the same time.

I'm calling this service like this:

const ValidatorA = (rule, value, callback) => {
  const serviceA = myService.someService(rule, value, callback);
  return serviceA;
};

const ValidatorB = (rule, value, callback) => {
  const serviceB = myService.someService(rule, value, callback);
  return serviceB;
};

ValidatorA and ValidatorB are linked to different inputs in template and runs almost at the same time. (1s delay)

What I would like to achieve is that ValidatorA and ValidatorB will call myService.someService independently, so there should be two calls at the same time. Currently it calls only once (from ValidatorB as it is called one second later). I suppose that ValidatorB is overwritting call from ValidatorA.

Creating two the same methods is solving this problem, however I believe that there is more elegant solution. Object.assign or _deepClone is not solving problem either.

Thank you!

1 Answers1

0

I think you can wrap someServices in a function

export default {
    getServices: function() {
      return 
        _.debounce(
        function  someService(rule, value, callback) {
          myApi.get(
            `check-input/${value}`,
          )
          .then((response) => {
            if (response.data.valid) {
              callback();
            } else {
              callback(new Error('Invalid value'));
            }
          })
          .catch(() => {
            callback(new Error('Internal error. Please try later.'));
          });
      },2000)
     }
};

and then

const ValidatorA = (rule, value, callback) => {
  const serviceA = myService.getServices()(rule, value, callback);
  return serviceA;
};

const ValidatorB = (rule, value, callback) => {
  const serviceB = myService.getServices()(rule, value, callback);
  return serviceB;
};
ittus
  • 21,730
  • 5
  • 57
  • 57