简体   繁体   中英

How to check multiple inequality from asynchronous data?

I have a node.js program that sends a POST request to a server every 5 second and gets the value for a data I want and track it.For example if it goes above certain number send log message and if it gets even higher call another function (eventually I want to set 5 or more thresholds). My question is what do I do if I want to track multiple thresholds for it?

The way I have it now is there is setInterval function calling my getValue(limit) every 5 second where the limit is the limit I want and if the limit is bypassed another function is called and I don't want to call getValue multiple times since its redundant.

const request = require('request');

function getValue(limit){
    var JSONobject = {'ContractCode':   contractCode};
    request({
      url: getUrl,
      method: "POST",
      json: true,
      headers: {
        'content-type': 'application/json; charset = UTF-8'
      },
      body: JSONobject
    }, function (error, response, body) {
        var obj = JSON.parse(JSON.stringify(response));
        if(obj.body.d.LastTradedPrice > limit){
        console.log('passed the point : %d', obj.body.d.LastTradedPrice);
        }

    });
}

Thank you

I m not sure about the question. What I can relate you want to call a function in some frequency. which collect data from another server. The other function will call this to get latest data. For this kind of problem you can think of using rxjs.

Here is the simple rxjs example.

// Source.js

const Rx = require('rxjs');
const dataStream = new Rx.BehaviorSubject();
export.getLatestData = () => {
  return dataStream.asObservable();
};
const getData = (cb) => {
  setTimeout(() => {
    cb(Math.random());
  }, Math.random() * 10000)
};
setInterval(() => {
  getData((data) => {
    dataStream.next(data);
  })
});

// Here getLatestData will return latest value

// Subscriber.js // On some event or call

const src = require('source');
route.get('/getData', () => {
  src.getLatestData().subscribe((latestData) => {
    console.log(`latestData:${latestData}`);
  })
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM