How to lock (Mutex) in NodeJS?

后端 未结 1 527
攒了一身酷
攒了一身酷 2021-01-29 00:15

There are external resources (accessing available inventories through an API) that can only be accessed one thread at a time.

My problems are:

  1. NodeJS serve
相关标签:
1条回答
  • 2021-01-29 00:23

    I'd use something like the async module's queue and set its concurrency parameter to 1. That way, you can put as many tasks in the queue as you need to run, but they'll only run one at a time.

    The queue would look something like:

    var inventoryQueue = async.queue(function(task, callback) {
        // use the values in "task" to call your inventory API here
        // pass your results to "callback" when you're done
    }, 1);
    

    Then, to make an inventory API request, you'd do something like:

    var inventoryRequestData = { /* data you need to make your request; product id, etc. */ };
    inventoryQueue.push(inventoryRequestData, function(err, results) {
        // this will be called with your results
    });
    
    0 讨论(0)
提交回复
热议问题