简体   繁体   English

从async.waterfall分配全局变量

[英]Assign global variable from async.waterfall

How could I assign value to a global variable from async.waterfall that is inside of setTimeout ? 如何从setTimeout内的async.waterfall将值分配给全局变量?

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 . 因此,基本上,我想从async.waterfall内设置全局变量。 That variable theVar will then be the timeout in setTimeout . 该变量theVar将成为setTimeout的超时。 Now theVar is always null . 现在, theVar始终为null

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. X秒钟后,您将启动异步功能。 At some point after that you will get a value out of it. 在那之后的某个时候,您将从中获得价值。 Only then will you know what X should be. 只有这样,您才知道X应该是什么。

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 (ie that the time you would have wanted to run the function will have passed while you waited for the async calculation to finish). 当然,由于您无法预测第2步和第3步之间的时间,因此在第4步中获得的值可能为负(即,您等待运行该函数的时间将在等待时过去以完成异步计算)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM