简体   繁体   中英

Javascript queue a function after another completes

I have a long running function A(). And my function B(){} can be called anytime.

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. And then run B.

I thought about promise.then(), but B may not necessarily be called after A. So it is not much useful in this situation.

How to 'queue' B to ensure the logic?

Do something like this: Define a variable var inQueue = 0 ; When A starts, set a variable inQueue = 1 , when it finishes, set it to inQueue = 0 . Now place a check like

if(!inQueue) B();

This will ensure B won't interrupt A.

Use a variable that is true when A is running and is set to false at the end of A . Check that within B . If it is running, have it wait a second and call B again.

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() . Just write them as you would normally to perform their duties.

Just implement a queue in the form of a dynamically updated promise chain.

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 :

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).
  • you needn't worry whether functions passed to queue() are synchronous or asynchronous. It will work with either.

DEMO

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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