提问者:小点点

使用nodejs的事件之间的条件


我有很少的on事件,我需要把if条件放在它们之间,所以如果条件不满足,代码将不会继续下一个事件。例如,如果当前价格>;50不继续到下一个打开。示例:

}).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',
  );

共1个答案

匿名用户

您可以将此呼叫包装成一个承诺,并在满足您的条件后立即拒绝/解决。然后,函数调用者可以等待返回的承诺并继续您的程序

   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()
   });
}

上面的示例将只在tickPrice事件中的price为50时才解析,并继续等待其他情况下的事件

作为一个例子,我在next valid id的末尾添加了一个解析。在您的代码中,您将probs有一个结束事件,您将为该事件添加最后一个解析