javascript - How to make sure that execution of a sync function happens after 3 asynchronous functions are completely done -


how make sure self.loadable() executed after 3 asynchronous requests complete. ???

var imghtml = "<span class='pull-right' style='padding-right:25px'><img alt='track' src='app/images/icons/track.png'><img alt='expand' src='app/images/icons/expand.png'></span>";              var request1 = {};             if(self.serviceid != null)                 request1.healthissue = {id:self.serviceid};              request1.location = {id:self.locationid};             request1.time = {id:header.defaultduration().value};             request1.hospital = {id:header.defaulthospital().value};             request1.query = {groupname:'speciality', dimension:'visits', viewby:'marketshare'};              console.log(request1);              server.fetchdata(request1).done(function(data){                       console.log('the specialty marketshares : ');                 console.log(data);                  if(data.length != 0) {                     $.each(data, function(index,mshare){                         var count = 0;                         $.each(self.marketsharetable(), function(index, tobj) {                             if(tobj.specialty == mshare.name){                                 tobj.marketshare(mshare.value);                                 count++;                                 return false;                             }                            });                         if(count == 0){                             var obj = {};                             obj.specialty = mshare.name;                             obj.marketshare = ko.observable(mshare.value);                             obj.rank = ko.observable();                             obj.volume = ko.observable();                             obj.btns = imghtml;                              self.marketsharetable.push(obj);                         }                      });                     console.log(self.marketsharetable());                 }                 else{                     console.log("clearing table");                     $('#msharetable').datatable({                         "paging":   false,                                           "info":     false,                         "destroy": true,                         "data": self.marketsharetable(),                         "language": {                             "emptytable": "no data available"                         }                        });                 }              });              var request2 = {};             if(self.serviceid != null)                 request2.healthissue = {id:self.serviceid};             request2.location = {id:self.locationid};             request2.time = {id:header.defaultduration().value};             request2.hospital = {id:header.defaulthospital().value};             request2.query = {groupname:'speciality', dimension:'visits', viewby:'rank'};                         server.fetchdata(request2).done(function(data){                              console.log('the specialty ranks : ');                 console.log(data);                  $.each(data, function(index,mrank){                     var count = 0;                     $.each(self.marketsharetable(), function(index, tobj) {                         if(tobj.specialty == mrank.name){                             tobj.rank(mrank.value);                             count++;                             return false;                         }                     });                     if(count == 0){                         var obj = {};                         obj.specialty = mrank.name;                         obj.marketshare = ko.observable();                         obj.rank = ko.observable(mrank.value);                         obj.volume = ko.observable();                         obj.btns = imghtml;                          self.marketsharetable.push(obj);                     }                  });                 console.log(self.marketsharetable());               });              var request3 = {};             if(self.serviceid != null)                 request3.healthissue = {id:self.serviceid};             request3.location = {id:self.locationid};             request3.time = {id:header.defaultduration().value};             request3.hospital = {id:header.defaulthospital().value};             request3.query = {groupname:'speciality', dimension:'visits', viewby:'count'};                        server.fetchdata(request3).done(function(data){                              console.log('the specialty input volumes : ');                 console.log(data);                     $.each(data, function(index,mvolume){                     var count = 0;                     $.each(self.marketsharetable(), function(index, tobj) {                         if(tobj.specialty == mvolume.name){                             tobj.volume(mvolume.value);                             count++;                             return false;                         }                        });                     if(count == 0){                         var obj = {};                         obj.specialty = mvolume.name;                         obj.marketshare = ko.observable();                         obj.rank = ko.observable();                         obj.volume = ko.observable(mvolume.value);                         obj.btns = imghtml;                          self.marketsharetable.push(obj);                     }                  });                 console.log(self.marketsharetable());                   $('#msharetable').datatable({                     "paging":   false,                                       "info":     false,                     "destroy": true,                                         "data": self.marketsharetable(),                     "language": {                         "emptytable": "no data available"                     },                     "deferrender": true,                     "columns": [                                 { "data": "specialty" },                                 { "data": "marketshare" },                                 { "data": "rank" },                                 { "data": "volume" },                                 { "data": "btns" }                      ]                                    });              });           self.loadtable(); 

please how execute sync function after 3 asynchronous calls server. new advanced javascript. suggest pls?

in javascript when invoke scynchronous function, returns promise. can see in code server.fetchdata(request) calls return promises, because use .done typicall in promises.

you can store promise in variable, this:

var promise1 = server.fetchdata(request); 

and use later this:

promise1.done(function() { /* code here */ }); 

the function inside done run when promise fulfilled. responsibility fulfilling (or rejecting) promise inside asynchronous method. i.e. when request finishes, , response has arrived, asynchronous method fulfill promise. and, int case, fulfill providing response callback i.e.

promise.done(function(response) { /* use response here */}); 

you can learn more promises looking @ jquery docs on deferred (which jquery way of implementing promise) or googling "javascript promises". deferred has functionality of promise, , methods fulfilling (resolve) or rejecting (reject) promise, can returned calling .promise() method of deferred.

for example asynchronouse method couldlook this:

function asynch() {     var deferred = $.deferred();     // asynchronous, , data         // if result ok, fulfill promise         deferred.resolve(data);         // if failed, reject         deferred.reject(reason);     return deferred.promise();  }; 

the idea that, if invoke method, inmediately return promise. and, when asynchronous code (like ajax call) finishes, method returned reject or resolve promise. when happens done or fail callbacks attached promise invoked.

now know basics, jquery offers way of composing promises, jquery.when(). write code this:

var promise1 = server.fetchdata(request1); var promise2 = server.fetchdata(request2); var promise3 = server.fetchdata(request3);  $.when(promise1, promise2, promise3)   .done(function(result1, result2, result3) {      // use results of 3 server.fetchdata here   }) 

the done part run if 3 promises fulfilled.if of them fails, not run @ all.

you should handle .fail of promises. server.fetchdata fail because of several reason, , code should handle problems.

there interesting promise libraries, like q, , natively supported in modern browsers: native promises. share basic concepts, defined in promises/a+.


Comments

Popular posts from this blog

sql - VB.NET Operand type clash: date is incompatible with int error -

SVG stroke-linecap doesn't work for circles in Firefox? -

python - TypeError: Scalar value for argument 'color' is not numeric in openCV -