首页 > 解决方案 > 使用nodejs的事件之间的条件

问题描述

我的事件很少,我需要在它们之间加上 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',
  );

标签: node.js

解决方案


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

   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 事件中价格为 50 时才会解析,否则继续等待事件

例如,我在下一个有效 ID 的末尾添加了一个解析。在您的代码中,您可能会有一个结束事件,您将为其添加最后一个解析


推荐阅读