0

I have a method which I called like

if(validate()){
   //save
}else{
  //show error
}

validate method calls a series of methods and all were synchronous calls, now a requirement has come where we also want to make ajax calls and perform some validations.

validate method is called in lots of pages, I want to limit the number of changes.

Basically I need suggestion how can I limit the change, I can put up a new design all together, I used jQuery deferred/promise which led to

var validPromise = validate();
validPromise.done(function(valid){
  ...........
});

But this would require change to be applied on every page.

validate() method is added using jQuery as follows

$.fn.validate()

Thanks in advance, looking for tips, suggestions if some damage control can be done, I am out of ideas with my limited JS knowledge.

baba.kabira
  • 3,111
  • 2
  • 26
  • 37
  • Since you're switching from synchrounoous to asynchronous, it's pretty normal that you have to change it everywhere. But at least this is a rather easy change to implement. – Walfrat May 30 '16 at 12:46
  • [this post](http://stackoverflow.com/a/20750164/456135) may help – Anupam May 30 '16 at 12:57
  • If you have to do async stuff, I truly do not think there is any other solution than modifying your code everywhere. One "solution" is to avoid async call. It is for example possible to create a blocking AJAX call with jQuery (use `async: false` with [$.ajax](http://api.jquery.com/jquery.ajax/)). No need to say that it is generally a bad idea (everything will freeze while waiting for the request response). – Quentin Roy May 30 '16 at 13:06
  • Oh, and while you're at it, you may want to avoid using non standard promise (such as jQuery's). Promises are now natively supported by every major browsers and it is quite easy to transform from the non-standard stuff jquery is doing. Who knows, may be one day you'll want to use some of your code in a [plain js project](http://youmightnotneedjquery.com/). And also, [Deferred is considered an anti-pattern](https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html) and you should avoid them. – Quentin Roy May 30 '16 at 13:12

0 Answers0