I need to use a serial queue in my code. I found a queue implementation made by @jessetane which is used by a huge amount of projects. Does anyone know if setting the concurrency param to 1 would essentially make the queue serial and synchronous? Thank you
CodePudding user response:
setting the concurrency param to 1 would essentially make the queue serial and synchronous?
It would make it serial in the sense that the first job needs to complete first before the second will start.
But it will not make it synchronous -- which is a good thing.
For instance, if you had set concurrency to 1, and would execute the following:
q.push(function (cb) {
setTimeout(function () {
console.log('slow job finished')
cb()
}, 200)
})
q.push(function (cb) {
console.log('simple')
cb();
})
...then you can be assured that the output will have this order:
slow job finished
simple
This is the serial characteristic, but it is not synchronous. If you would have one more output statement, like here:
q.push(function (cb) {
setTimeout(function () {
console.log('slow job finished')
cb()
}, 200)
})
q.push(function (cb) {
console.log('simple')
cb();
})
console.log('hello')
...then the output will have:
hello
slow job finished
simple
This shows that the jobs are executed asynchronously, i.e. after the current call stack has been emptied.
CodePudding user response:
I think you misunderstand why this queue is set up as asynchronous
The point of having the queue be asynchronous is so you can wait for a new item to be added to the queue, and in the meantime JavaScript (which commonly uses a single thread) can be free to do other things than just wait for an item to appear on the queue