I'm working on a practice problem using setTimeOut and callbacks for the first time. This is the situation:
You receive a JavaScript object 'recordMap' of the following
type: { [recordName: string]: Client }
Client is an interface allowing to a) send a text message, b) receive a text message by registering a callback function.
interface Client {
sendMessage: (message: string) => void;
//to send messages to the Client
onMessage: (callback: (message: string) => void) =>
void; // a callback for receiving messages from the
Client
}
Public method 'initialize' will initialize the tracking of active Clients.
The goal is to make sure that no records in 'recordMap' are kept for inactive Clients.
//to register Send a 'ping' message to all Clients every 10 seconds. Register a callback function to receive messages from Clients.
Sending and receiving messages is an asynchronous form of communication - give Clients 3 seconds to reply to your message.
For every Client who hasn't replied with a 'pong' message, remove his record from 'recordMap'.
type RecordMap = { [recordName: string]: Client };
class RecordTracker {
constructor (private recordMap: RecordMap) {}
public initialize (): void {
...?
}
public getRecordMap (): RecordMap {
return { ...this.recordMap };
}
}
I feel like I need to use setInterval for a message every 10 seconds and setTimeOut to send and receive the message, but not sure where to go from there.
I'm not really sure where to go with this one. Do I need to create some dummy clients to call? This is what I have so far:
```
interface Client {
sendMessage: (message: string) => void;
onMessage: (callback: (message: string) => void) => void;
}
type RecordMap = { [recordName: string]: Client };
class RecordTracker {
constructor (private recordMap: RecordMap) {}
public initialize (): void {
setInterval(() => {
const sendMessage = (message) => {
//????
}
}, 10000)
}
public getRecordMap (): RecordMap {
return { ...this.recordMap };
}
}```
答案 0 :(得分:0)
我将从设计一个接受客户端并检查其是否仍处于活动状态的函数开始。熨平该部分后,将其直接连接到某种常规测试体系中应该很简单。
由于发送消息是异步的,因此我们的功能是异步的。并且,由于我们要强制解决此问题,因此我们将显式创建一个Promise,以便在超时后可以解决它。
以下是我的初衷:
async function getIsClientActive( client, timeoutMs ) {
return new Promise(resolve => {
// set up the timeout
setTimeout(() => resolve(false), timeoutMs)
// set up handler to listen for pong
const pongReceiver = ( msg ) => {
if(msg === 'pong') resolve(true)
}
client.onMessage = pongReceiver
// send the ping
client.sendMessage('ping')
})
}
一个大警告:我的getIsClientActive
认为劫持每个客户的onMessage
处理程序是安全的。如果这样做不安全,则可以在ping操作期间将当前处理程序临时存储在RAM中(更简单),或者为每个触发“消息”事件并且ping操作可以临时订阅的客户端设置一个EventEmitter(更可靠)
我要强调的一件事:如果此客户端探测操作可以不了解程序用来跟踪所有已知客户端的数据结构,它将使您的工作变得更容易。