[Node.js] Problems retrieving data from websockets

Asked 2 years ago, Updated 2 years ago, 36 views

Hello.

I'm posting like this because there's a problem with getting websocket data.

var ws = new WebSocket(`wss://${host}:${port}`);
var api = new api_call(ws);

function get_data(today){
    api_call.on('ready', () => {
        api_call.send({
            or_ordr_dt: today // today's date
        });
    });
    api_call.on('getData', (data) => { 
        console.log(JSON.stringify(data)); 
    });
};

get_data('20180830');

This is the basic structure of the API provided with the above code in the socket.It only gives data when sending 를.

As long as the program doesn't stop, the listener is still working.

I changed the code above to the form of continuous receipt by changing it as below.

function get_data_loop(today){
    api_call.on('ready', () => {
        function loop(){
            api_call.send({
                or_ordr_dt: today // today's date
            });
        };
        setInterval(()=>{
            loop();
        },1000);
    });
    api_call.on('getData', (data) => { 
        console.log(JSON.stringify(data)); 
    });
};
get_data_loop('20180830');

It's good to receive it continuously every second since I changed it like above, but now I have a situation where I have to call only once when I need it.

Is there any way to receive the above code only once when I want it?

For your information, if you call the code at the top to setInterval, there will be a listener error.

Just once when you want to.I think I can call send, but I can't think of a proper way.

ps. Not how to use if for the second code, such as if(isOn == true){loop();}It would be nice if there was a way to send it.

node.js

2022-09-22 16:44

1 Answers

Generally speaking, All websocket communication logic must operate after 'ready'.

If you write based on the code you wrote, just

const today = ‘20180830’;

api_call.on('ready', () => {
    setInterval(()=>{
        api_call.send({ or_ordr_dt: today });
    }, 1000);

    // Sign up for any event you want here
    something.on(‘event_type’, (date) => {
        api_call.send({ or_ordr_dt: date })
    });
});

api_call.on('getData', (data) => { 
    console.log(JSON.stringify(data)); 
});

After the asynchronous socket handshake in this way, the main logic should come out from the 'ready' event handler.

If you try to take the structure you wrote as it is, it becomes difficult to understand what should come first, making it difficult to write the code. However, the main thread cannot wait for the web socket to be ready.(blocking)

If you really need synchronization logic, you can try using async/away, but it seems better to take the code flow itself differently like above than to take such a hard time.


2022-09-22 16:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.