我在服務器端回圈中有異步作業:
const contacts = [];
for(contact of contacts){
(async () => {
await MailService.sendMessage(contact, 'message body')
})()
}
我想使用客戶端打破回圈,我要做的是:
1 . 從服務器端,在 sendMessage 之前,檢查廣播狀態是行程還是停止,如果停止,則中斷回圈。
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')
})
有用。但這不會使服務器很重嗎?因為在每個回圈中我都必須檢查資料庫。
我還有其他方法可以停止回圈嗎?無需檢查資料庫。
uj5u.com熱心網友回復:
你不需要資料庫——你只需要更新一個可以在服務器代碼中看到的值。您可以有一個普通的 Express 路由,將客戶端會話 ID 添加到集合中,該集合會在呼叫路由時更新。然后,讓您的回圈檢查該客戶端是否發送了這樣的請求。
使用session,您可以擁有類似的路線:
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')
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/404746.html
標籤:
下一篇:降低演算法復雜度的方法
