Search code examples
javascriptconcurrencyqueue

Making asynchronous queue serial and synchronous


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


Solution

  • 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.