javascript中的信号量类队列? [英] Semaphore-like queue in javascript?

查看:90
本文介绍了javascript中的信号量类队列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个变量 can_run ,可以是1或0,然后我有一个函数队列,应该在变量切换后立即运行从 0 1 (但一次只能使用1个这样的函数)。

I have a variable can_run, that can be either 1 or 0, and then I have a queue of functions, that should be run as soon as the variable is switched from 0 to 1 (but only 1 such function at a time).

现在,我所做的是

var can_run=1;
function wait_until_can_run(callback) {
    if (can_run==1) {
        callback();
    } else {
        window.setTimeout(function(){wait_until_can_run(callback)},100);
    }
}

//...somewhere else...

wait_until_can_run( function(){
   can_run=0;
   //start running something
});

//..somewhere else, as a reaction to the task finishing..
can_run=1;

然而,它不会让我非常高效地持续运行大约100次超时。像信号量这样的东西在这里会很方便;但一般来说,JavaScript中并不真正需要信号量。

It works, however, it doesn't strike me as very efficient to have about 100 timeouts continuously running. Something like semaphore would be handy in here; but in general, semaphores are not really needed in JavaScript.

那么,在这里使用什么?

So, what to use here?

编辑:我写了函数队列但是如此处所见,我并不关心订单。

edit: I have written "queue of functions" but as seen here, I don't really care about the order.

推荐答案

这里是一个很好的队列类,你可以使用没有使用超时:

Here is a nice Queue class you can use without the use of timeouts:

var Queue = (function () {

    Queue.prototype.autorun = true;
    Queue.prototype.running = false;
    Queue.prototype.queue = [];

    function Queue(autorun) {
        if (typeof autorun !== "undefined") {
            this.autorun = autorun;
        }
        this.queue = []; //initialize the queue
    };

    Queue.prototype.add = function (callback) {
        var _this = this;
        //add callback to the queue
        this.queue.push(function () {
            var finished = callback();
            if (typeof finished === "undefined" || finished) {
                //  if callback returns `false`, then you have to 
                //  call `next` somewhere in the callback
                _this.dequeue();
            }
        });

        if (this.autorun && !this.running) {
            // if nothing is running, then start the engines!
            this.dequeue();
        }

        return this; // for chaining fun!
    };

    Queue.prototype.dequeue = function () {
        this.running = false;
        //get the first element off the queue
        var shift = this.queue.shift();
        if (shift) {
            this.running = true;
            shift();
        }
        return shift;
    };

    Queue.prototype.next = Queue.prototype.dequeue;

    return Queue;

})();

可以这样使用:

// passing false into the constructor makes it so 
// the queue does not start till we tell it to
var q = new Queue(false).add(function () {
    //start running something
}).add(function () {
    //start running something 2
}).add(function () {
    //start running something 3
});

setTimeout(function () {
    // start the queue
    q.next();
}, 2000);

小提琴演示: http://jsfiddle.net/maniator/dUVGX/

更新至使用es6和new es6 Promises:

Updated to use es6 and new es6 Promises:

class Queue {  
  constructor(autorun = true, queue = []) {
    this.running = false;
    this.autorun = autorun;
    this.queue = queue;
    this.previousValue = undefined;
  }

  add(cb) {
    this.queue.push((value) => {
        const finished = new Promise((resolve, reject) => {
        const callbackResponse = cb(value);

        if (callbackResponse !== false) {
            resolve(callbackResponse);
        } else {
            reject(callbackResponse);
        }
      });

      finished.then(this.dequeue.bind(this), (() => {}));
    });

    if (this.autorun && !this.running) {
        this.dequeue();
    }

    return this;
  }

  dequeue(value) {
    this.running = this.queue.shift();

    if (this.running) {
        this.running(value);
    }

    return this.running;
  }

  get next() {
    return this.dequeue;
  }
}

它可以以相同的方式使用:

It can be used in the same way:

const q = new Queue(false).add(() => {
    console.log('this is a test');

    return {'banana': 42};
}).add((obj) => {
    console.log('test 2', obj);

    return obj.banana;
}).add((number) => {
    console.log('THIS IS A NUMBER', number)
});

// start the sequence
setTimeout(() => q.next(), 2000);

虽然现在这次传递的值是一个promise等或一个值,但它会被传递给下一个功能自动。

Although now this time if the values passed are a promise etc or a value, it gets passed to the next function automatically.

小提琴: http:// jsfiddle .net / maniator / toefqpsc /

这篇关于javascript中的信号量类队列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆