node.js - 使用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',
);
解决方案
您可以将此调用包装到一个承诺中,并在满足您的条件后立即拒绝/解决。然后函数调用者可以等待返回的承诺并继续您的程序
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 的末尾添加了一个解析。在您的代码中,您可能会有一个结束事件,您将为其添加最后一个解析
推荐阅读
- mongodb - 如何从 mongo 查询/投影返回格式化的响应?
- python - 程序在 python 中无法正常工作的问题
- amazon-web-services - 如果它们不是架构中的所有者,则 Redshift 隐藏对象/表
- reactjs - 将 POST 数据从 react 发送到 Django-rest -framework 显示 415 错误
- python - 如何按频率对给定程序进行排序?[按升序排列]
- types - OCaml 编译器需要一个不相关的自定义类型
- godot - Godot - 如何让我的块在玩家周围生成 3 x 3 网格
- wordpress - Wordpress - 基于角色的子主题切换
- reactjs - 使用 Styled 组件和 rc-year-calendar 做出反应
- sql - 加入以获取其他表中没有值的项目会给出多个结果