简体   繁体   English

Javascript将函数逐个完成

[英]Javascript queue a function after another completes

I have a long running function A(). 我有一个长时间运行的函数A()。 And my function B(){} can be called anytime. 而且我的函数B(){}可以随时调用。

Note function B doesn't have to be called after A. But if it is called and if A is running, then A must be finished. 注意,不必在A之后调用函数B。但是,如果调用了函数B并且正在运行A,则必须完成A。 And then run B. 然后运行B。

I thought about promise.then(), but B may not necessarily be called after A. So it is not much useful in this situation. 我考虑过promise.then(),但是不一定要在A之后调用B。因此在这种情况下它没有太大用处。

How to 'queue' B to ensure the logic? 如何“排队” B以确保逻辑?

Do something like this: Define a variable var inQueue = 0 ; 做这样的事情:定义一个变量var inQueue = 0 ; When A starts, set a variable inQueue = 1 , when it finishes, set it to inQueue = 0 . 当A开始时,设置变量inQueue = 1 ,完成时将其设置为inQueue = 0 Now place a check like 现在放一张像

if(!inQueue) B();

This will ensure B won't interrupt A. 这将确保B不会中断A。

Use a variable that is true when A is running and is set to false at the end of A . 使用一个变量, trueA正在运行并设置为false ,在结束A Check that within B . B检查。 If it is running, have it wait a second and call B again. 如果正在运行,请稍等片刻,然后再次致电B

var isARunning

A() {
  isARunning = true
  //do the things
  isARunning = false
}

B() {
  if (isARunning) {
   setTimeout(() => { B() }, 1000);
  }
  else {
    // do more things
  }
}

Don't use flags! 不要使用标志! They are completely unnecessary. 它们是完全不必要的。

Also don't do anything special in A() or B() . 也不要在A()B()做任何特殊的事情。 Just write them as you would normally to perform their duties. 只需像平时执行任务一样写它们即可。

Just implement a queue in the form of a dynamically updated promise chain. 只需以动态更新的Promise链的形式实现队列。

var q_ = Promise.resolve();

function queue(fn) {
    q_ = q_.then(fn);
    return q_;
}

Now you can queue A and B , or any other function, as follows : 现在,您可以AB或任何其他函数排队,如下所示:

queue(A);
queue(B);
queue(someOtherFunction);

Or, if you need to pass parameters : 或者,如果您需要传递参数:

queue(A.bind(null, 'a', 'b', 'c'));
queue(B.bind(null, 'x', 'y', 'z'));
queue(someOtherFunction.bind(null, 1, 2, 3));

As a bonus, 作为奖励,

  • A() and B() (and other functions) remain available to be called directly (unqueued). A()B() (以及其他函数)仍然可以直接调用(未排队)。
  • you needn't worry whether functions passed to queue() are synchronous or asynchronous. 您不必担心传递给queue()函数是同步的还是异步的。 It will work with either. 它将与任一。

DEMO 演示

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

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