Understanding JavaScript Processing Registration Patterns

Asked 1 years ago, Updated 1 years ago, 31 views

I don't know how to implement it, so I'd like to ask you a question.

The code below is the code that connects to the websocket server that runs the current time.
"A function X is registered and executed at N seconds per minute."However, if I want to cancel my registration every hour and M minutes, how should I implement it?"

I wrote it myself, but I can't wait for the wait to complete the process, or I'd like to get some advice because it's going to be a callback hell.

 constws=newWebSocket('wss://websocketstest.com/service');
ws.onopen=()=>{
    ['connected,', 'version, hybi-draft-13', 'echo, test message', 'timer,']
        .forEach(c=>ws.send(c));
};

let events = [ ]
ws.onmessage=(blob)=>{
        if(events.length===0)return;
        const messageDate = new Date(blob.data.split(',')[1]);
        for (const event of events) {
            if(event.func(messageDate)===true){
                event.valid=false;
            }
        }
        events=events.filter(s=>s.valid===true);
}

function register(func){
    events.push({
        func: func,
        valid —true
    });
}

const N = 30;
const M = 5;
const X=()=>{console.log("FOFOFOOOOOO);};
(async() = > {
    register(msg=>{
        console.log(msg);
        if(msg.getSeconds()%N===0){
            X()
        }
        if(msg.getHours()%M===0){
            return true; // exit
        }
    });
    console.log('end');
})();

javascript

2022-09-30 20:24

2 Answers

I think it would be better to make it in the Observer/Observable pattern.Observer registers with Observable, and Observable sends a message to subscribers at any time.

DEMO

ws.onopen=()=>{
    ['connected,', 'version, hybi-draft-13', 'echo, test message', 'timer,']
        .forEach(c=>ws.send(c));
};

I didn't understand this part well, so I left it as it is.

Wait can't wait for the process to complete.

wait can only be used for the Promise object, so you need to create a function that returns Promise, but you don't have to use it separately.

Callback hellish code

I don't think it's going to be a callback hell because there's no need for a callback chain at this time.


2022-09-30 20:24

The original code is complicated, but can't I use the following?

ws.onmessage=(blob)=>{
  const msg = new Date(blob.data.split(',')[1]);
  if(msg.getMinutes()< M) {
    if(msg.getSeconds()===S){X();}
  }
}


2022-09-30 20:24

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.