deals4us3
deals4us3

Reputation: 35

condition between on events using nodejs

I have few on events and I need to put if condition in between them so if condition is not met the code will not continue the the next events. for example if current price> 50 do not continue to the next on. example:

}).on('tickPrice', function (tickerId, tickType, price, canAutoExecute) {
  currentPrice = price
  tickType=tickType
  console.log(
    '%s %s%d %s%d %s%s',
    chalk.cyan(util.format('[%s]', ib.util.tickTypeToString(tickType))),
    chalk.bold('tickerId='), tickerId,
  );
}).on('nextValidId', function (orderId) {
  console.log(
    '%s %s%d',
  );

Upvotes: 1

Views: 54

Answers (1)

Edward Romero
Edward Romero

Reputation: 3106

You could wrap this call in to a promise and reject/resolve as soon as your condition is met. The function caller can then await the promise returned and continue your program

   function streamer() {
         return new Primise((resolve, reject) => {
          ....// your initial code here 

   }).on('tickPrice', function (tickerId, tickType, price, canAutoExecute) {
     currentPrice = price
     tickType=tickType
     console.log(
'%s %s%d %s%d %s%s',
         chalk.cyan(util.format('[%s]', ib.util.tickTypeToString(tickType))),
         chalk.bold('tickerId='), tickerId,
     );


     if(price > 50) {
        return resolve();
     }

    }).on('nextValidId', function (orderId) {
        console.log('%.s %s%d',
        );

    ...// rest of your code 
    
    return resolve()
   });
}

The above example will resolve only then price is 50 inside the tickPrice event, and continue to wait for events other wise

I added a resolve at end of next valid id as an example. In your code you would probs have an end event for which you would add the last resolve

Upvotes: 1

Related Questions