Tomas Gonzalez Tomas Gonzalez - 1 year ago 53
Node.js Question

Handle events. One by one. Node.js

I have got this event listener:

manager.on('newOffer', (offer) => {
console.log(`We have a new offer :#${offer.id}`.bgGreen);
getInventory( function(){
processTradeOffer(offer);});});


My problem born when many 'newOffers' appear. They cannot been process correctly because the program is firing 'newOffers' withouting process first.

What I need(In my opinion): When an 'newOffer' appear, turn off the event listener, complete functions and then turn on again. Is that possibly?

Answer Source

Sound like you need a queue with a concurrency of 1, something that async.queue() can provide:

const handler = (offer, done) => {
  console.log(`We have a new offer :#${offer.id}`.bgGreen);
  getInventory(() => {
    processTradeOffer(offer); // NB: if this is async, pass a callback that calls `done`
    done();
  });
};

const queue = require('async').queue(handler, 1);

...

// Add a new offer to the queue:
let offer = new Offer(); // or however you create `offer` objects
queue.push(offer);

(however, this could become a bottleneck if you can't handle offers fast enough, in which case you may need to rethink how offers get handled)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download