Home > Back-end >  Stop/Break looping from server side with client side?
Stop/Break looping from server side with client side?

Time:01-07

I have async job inside looping from server side:

const contacts = [];

for(contact of contacts){
    (async () => {
        await MailService.sendMessage(contact, 'message body')
    })()
}

I want to break that looping using client side, what i do is:

1 . from server side, before sendMessage, check if Broadcast status is process or stopped, if stopped, than break looping.

2 . from client side, if i want to stop the Broadcast(stop looping), i need to update Broadcast value from process to stopped.

So, my code should be:

server side:

const contacts = [];

for(contact of contacts){
    (async () => {
        const currentBroadcast = await Broadcast.findById('id')
        if(currentBroadcast.status === 'stopped') break;

        await MailService.sendMessage(contact, 'message body')
    })()
}

client side:

document.getElementById('stop').addEventListener('click', () => {
    fetch('url/broadcast/stop/:id')
})

it works. But wouldn't that make the server heavy? Because in every loop I have to check into the database.

is there any other way i can do to stop the looping? without having to check into the database.

CodePudding user response:

You don't need a database for that - you just need to update a value that can be seen in the server's code. You could have a plain Express route that adds client session IDs to a collection, which gets updated when the route is called. Then, just have your loop check whether that client's sent such a request.

With sessions, you could have something like

For example, you could have a route

const stoppedBroadcastSessionIds = new Set();
app.post('/stopbroadcast', function (req, res) {
  stoppedBroadcastSessionIds.add(req.session.id);
})

and then do

for(const contact of contacts){
  if (stoppedBroadcastSessionIds.has(req.session.id)) break;
  await MailService.sendMessage(contact, 'message body')
}
  •  Tags:  
  • Related