javascript - Approach to check if callback was last fired? -


i have function looks that:

function update() {     buildupdate(function(result) {         // send result clients     }); } 

this works correctly. if like:

// data state 1  update(); // time, buildupdate() won't take long time  // work resulting in: // data state 2  update(); // time, buildupdate() take long time           // , finish after third call  // work resulting in: // data state 3  update(); // time, buildupdate() won't take long time 

as expected, clients receive 3 updates. in wrong order because third call of update() did finish earlier second. clients point of view looks this:

  • receives update calculated based on data state 1
  • receives update calculated based on data state 3
  • receives update calculated based on data state 2 (this update should not sent)

is there design pattern or function helps avoid such case?

note: doesn't matter if client doesn't receive updates. matters last 1 received must consistent current data state.

my idea generate on each invocation of update() random id. afterwards check in callback whether id matches last 1 generated. generation of id introduces new async calculation , leads more code on each usage.

the easiest add callback

function update(callback) {     buildupdate(function(result) {         // send result clients          if (typeof callback == 'function') callback();     }); } 

and do

 update(function() {           // when first 1 finishes      update(function() {       // run second 1          update(function() {   // , when second finished, third               update();        // , on....          });      });  }); 

if add async middleware have more advanced methods available deal async behaviour.


Comments

Popular posts from this blog

html - Sizing a high-res image (~8MB) to display entirely in a small div (circular, diameter 100px) -

java - IntelliJ - No such instance method -

identifier - Is it possible for an html5 document to have two ids? -