nodejs隊列

nodejs隊列

創建具有指定併發性的隊列對象。添加到隊列的任務以並行方式處理(直到併發性限制)。如果所有的worker都在進行中,任務就會排隊,直到有一個worker可用。worker完成任務後,將調用該任務的回調。

priorityQueue對象,queue和priorityQueue對象有兩個區別: push(任務,優先級,[回調])-優先級應該是一個數字。如果給定了一組任務,則所有任務將被分配相同的優先級。沒有unshift 。

// create a queue object with concurrency 2
var q = async.queue(function(task, callback) {
    console.log('hello ' + task.name);
    callback();
}, 2);

// assign a callback
q.drain(function() {
    console.log('all items have been processed');
});
// or await the end
// await q.drain()

// assign an error callback
q.error(function(err, task) {
    console.error('task experienced an error');
});

// add some items to the queue
q.push({name: 'foo'}, function(err) {
    console.log('finished processing foo');
});
// callback is optional
q.push({name: 'bar'});

// add some items to the queue (batch-wise)
q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) {
    console.log('finished processing item');
});

// add some items to the front of the queue
q.unshift({name: 'bar'}, function (err) {
    console.log('finished processing bar');
});
//--------------------------
// create a queue object with concurrency 1
var q = async.priorityQueue(function(task, callback) {
  console.log('Hello ' + task.name);
  callback();
}, 1);

// assign a callback
q.drain = function() {
  console.log('All items have been processed');
};

// add some items to the queue with priority
q.push({name: 'foo3'}, 3, function(err) {
  console.log('Finished processing foo');
});

q.push({name: 'bar2'}, 2, function (err) {
  console.log('Finished processing bar');
});

// add some items to the queue (batch-wise) which will have same priority
q.push([{name: 'baz1'},{name: 'bay1'},{name: 'bax1'}], 1, function(err) {
  console.log('Finished processing item');
});
輸出結果如下:
hello bar
finished processing bar
hello foo
finished processing foo
hello bar
hello baz
finished processing item
hello bay
finished processing item
hello bax
finished processing item
all items have been processed
Hello bay1
Finished processing item
Hello bax1
Finished processing item
Hello bar2
Finished processing bar
Hello foo3
Finished processing foo

參考:
https://github.com/caolan/async/blob/v1.5.2/README.md
https://medium.com/velotio-perspectives/understanding-node-js-async-flows-parallel-serial-waterfall-and-queues-6f9c4badbc17

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章