0

How could I assign value to a global variable from async.waterfall that is inside of setTimeout?

Here is a part of my code:

var theVar = null;

setTimeout(function () {
 async.waterfall([
      function (next) {
        var thedata = 1;
        next(null,thedata);
      },
      function (thedata,next) {
        if (thedata === 1) {
            theVar = 2;
        }
        theVar = 3;
        next();
 ], function (err, result) {

 });
}, theVar * 1000); //theVar is timeout here.

So, basically, I want to set global variable from within async.waterfall. That variable theVar will then be the timeout in setTimeout. Now theVar is always null.

user1665355
  • 3,324
  • 8
  • 44
  • 84

1 Answers1

0

You can't.

Leaving aside the usual issues of returning from an asynchronous call

You are trying to do some pretty serious time travel here.

After X seconds, you will start an asynchronous function. At some point after that you will get a value out of it. Only then will you know what X should be.

That's impossible (due to the limitations of causality in general rather than programming specifically).


What would be possible would be to:

  1. Store the current time
  2. Start an asynchronous function
  3. When you got a result from that function, use it to determine an interval
  4. Subtract the difference between "now" and the stored time from the interval
  5. Set a timeout to do something else using that computed time

Of course, since you can't predict the time between steps 2 and 3, it is possible that the value you get in step 4 will be negative (i.e. that the time you would have wanted to run the function will have passed while you waited for the async calculation to finish).

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335