この解答例はChatGPTによって生成されています,正しいかは自己判断で。 皆の投稿からも解答例が見つかるかもしれませんよ。
BFE.devでのAI解答例 - JavaScript コーディング問題
171. create callback on message channel
class BetterChannel { constructor() { const { port1, port2 } = new SomeChannel(); this.port1 = port1; this.port2 = port2; const replies = {}; this.port2.onmessage = (message) => { const id = message.id; if (message.isReply) { if (id in replies) { replies[id](message.data); } } else { const reply = (data) => { const replyMessage = { id, isReply: true, data }; this.port1.postMessage(replyMessage); } this.port2.onmessage(message.data, reply); } } } postMessage(data, callback) { const id = Math.random().toString(); const message = { id, data }; this.port1.postMessage(message); if (callback) { const replyCallback = (data) => { delete replies[id]; callback(data) }; replies[id] = replyCallback; } }}
解説:
BetterChannel
コンストラクタはSomeChannel
を作成し、両方のポート (port1
,port2
) を保持します。replies
オブジェクトは、callback を送信する際に保持される返信を保持するために使用されます。port2.onmessage
ハンドラは、isReply
フラグをチェックして、メッセージが要求か返信かを判断どころです。- もし
isReply
フラグがtrue
であれば、関連するコールバックをreplies
オブジェクトから検索し、関連するデータを返信します。 - もし
isReply
フラグがfalse
であれば、指定されたデータとreply
関数を引数としてport2.onmessage
のハンドラが呼ばれます。
- もし
postMessage
メソッドは、ランダムな ID を生成し、返信がある場合はreplies
オブジェクトにコールバック関数を追加します。その後、メッセージを生成し、port1.postMessage()
を呼び出します。