How to stop the execution of a socket event when any user response to the event

406 Views Asked by At

I'm trying to develop a doctor-calling system like Uber for my university project. In this system, when a patient clicks a specific UI button in his app, a socket event, CallingForEmergencyDoctor is emitted.

When this event is triggered I receive it in the server and send a real-time notification/call to the Doctor app by emitting an event emergencyDoctorCall

According to my requirement, a doctor should only get the notification/call/alert for 5 sec. If the doctor does not answer the call, this event needs to be emitted to another doctor. In the meantime, if any doctor accepts the call, no other doctor will receive the call/notification.

I make an array, activeEmergencyDoctors containing all the active online doctors and emit the event using a loop. Then I use a sleep function to delay the time. Then after 5 sec, I emit another event emergencyCallDisconnect to the doctor to disconnect the call and disappear the accept button from the doctor's UI

 socket.on("CallingForEmergencyDoctor", (user) => {

    // send event to a specific user at a time
    for (let i = 0; i < activeEmergencyDoctors.length; i++) {
      socket.to(activeEmergencyDoctors[i].socketId).emit("emergencyDoctorCall");
      userId = activeEmergencyDoctors[i].userId;
      console.log(
        `Request sent to user ${i + 1} | userId: ${
          activeEmergencyDoctors[i].userId
        }`
      );
      sleep(5000);
      socket
        .to(activeEmergencyDoctors[i].socketId)
        .emit("emergencyCallDisconnect");
    }
    console.log("No doctor available");
  });

Everything is ok, every doctor is receiving call one after another. But how can I stop the execution of the for loop and receive the userId who accepts the request?

0

There are 0 best solutions below