Stop/Break 从服务器端循环到客户端?

Stop/Break looping from server side with client side?

我在服务器端循环内部有异步作业:

const contacts = [];

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

我想使用客户端打破循环,我所做的是:

1。从服务器端,在 sendMessage 之前,检查 Broadcast 状态是否为 processstopped,如果停止,则中断循环。

2。从客户端,如果我想停止广播(停止循环),我需要将广播值从进程更新为已停止。

所以,我的代码应该是:

服务器端:

const contacts = [];

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

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

客户端:

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

有效。但这不会使服务器变重吗?因为在每个循环中我都必须检查数据库。

有没有其他方法可以停止循环?无需检查数据库。

你不需要数据库 - 你只需要更新一个可以在服务器代码中看到的值。你可以有一个简单的 Express 路由,它将客户端会话 ID 添加到一个集合中,该集合在调用路由时得到更新。然后,让您的循环检查该客户端是否发送了这样的请求。

使用 sessions,你可以有类似的东西,有一条路线:

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

然后

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