JS: premature method return due to asynchronous function call

Status
Not open for further replies.

Kethinov

Ars Tribunus Militum
2,067
I've got some code which resembles this basic structure:

Code:
var a,

    async = function(f) {
      setTimeout(function() {
        var r = 'step 2';
        f(r);
      }, 1);
    },

    myFunc = function() {
      a = 'step 1';
      async(function(r) {
        a = r; // should reset "a" to "step 2" but doesn't finish in time
      });
      return a; // always returns step 1
    };

// always returns step 1
console.log(myFunc());

// returns step 2 now that async() is done executing
setTimeout(function() {
  console.log(a)
}, 2);

Assuming the hypothetical "async" function is completely unmodifiable library code, what can I do in "myFunc" to ensure that "a" gets properly set to "step 2" before the function returns?
 
I'm surprised that this library would not offer some sort of callback mechanism as that is normally the convention in javascript. You're essentially going to have to force execution to wait until the value has changed. You can do this with a flag and monitor it until it is true using while loop.

This is nasty IMO and not really a pattern I would recommend, ideally you would want a callback you can hook into

Code:
    myFunc = function() {
      a = 'step 1';
      async(function(r) {
        a = r; // should reset "a" to "step 2" but doesn't finish in time
      });
      while(a == 'step 1'){
       //force wait until a has changed
      }
      return a; // always returns step 1
    };
 

technophile

Ars Legatus Legionis
23,768
Nimajneb":l05u0dx3 said:
I'm surprised that this library would not offer some sort of callback mechanism as that is normally the convention in javascript. You're essentially going to have to force execution to wait until the value has changed. You can do this with a flag and monitor it until it is true using while loop.

This is nasty IMO and not really a pattern I would recommend, ideally you would want a callback you can hook into

Code:
    myFunc = function() {
      a = 'step 1';
      async(function(r) {
        a = r; // should reset "a" to "step 2" but doesn't finish in time
      });
      while(a == 'step 1'){
       //force wait until a has changed
      }
      return a; // always returns step 1
    };

You can get around the infinite loop here by doing something like this:
Code:
    myFunc = function() {
      a = 'step 1';
      async(function(r) {
        a = r; // should reset "a" to "step 2" but doesn't finish in time
      });
      var callback = function () {
        if(a == 'step 1'){
         setTimeout(callback, 500); // Timeout can be set to whatever granularity you like
         return;
        }
        return a; // always returns step 1
      };
      callback();
    };
 
Status
Not open for further replies.