不使用代理的可行方法是使用异步101 100的通用实现.后者可以被视为函数包装的特殊情况.
这样的修饰符接受两个函数proceed
和handler
以及target
对象作为其3个参数.它返回一个异步函数,该函数将再次返回(假定为异步)handler
(回调)函数的等待结果.后者确实在(可选的)提供的target
的上下文中被调用,同时还被传递给proceed
函数、其自己的handler
引用和修改后的函数的arguments
array.
因此,基于这样的修饰符,OP可以通过修改例如如下所示的客户端实例的sendMessage
-方法来实现预期的行为.
// client instantiation.
const telegramClient = new TelegramClient;
// client's handler modification.
telegramClient.sendMessage = asyncAround(
telegramClient.sendMessage,
ensureConnectedClient,
telegramClient,
);
...其中ensureConnectedClient
是handler
函数,它准确地实现了OP正在寻找的东西……
"... [ensure a] connect[ed client] before proceeding with the invocation of every other instance method of the TelegramClient class"个
...示例代码...
// implementation of the client specific async `around`-handler.
async function ensureConnectedClient(proceed, handler, args) {
const client = this;
// see:
// - [https://gram.js.org/beta/classes/TelegramClient.html#connected]
// - [https://gram.js.org/beta/classes/TelegramClient.html#disconnected]
// ... always ensure a connected client ...
if (client.disconnected()) {
console.log('+++ client needs to be reconnected +++');
await client.connect();
} else {
console.log('+++ client is still connected +++');
}
// ... before proceeding with any other method.
return (
await proceed.apply(client, args)
);
}
// client instantiation.
const telegramClient = new TelegramClient;
// client's method-modification.
telegramClient.sendMessage = asyncAround(
telegramClient.sendMessage,
ensureConnectedClient,
telegramClient,
);
// client's modified handler invocation.
telegramClient.sendMessage("Hello, Telegram!");
.as-console-wrapper { min-height: 100%!important; top: 0; }
<script>
// client implementation.
class TelegramClient {
async connect() {
console.log("Connecting to Telegram...");
// simulate some asynchronous work.
await new Promise(resolve => setTimeout(resolve, 1500));
console.log("Connected!");
}
disconnected() {
// simulate a connect-state method via random boolean.
return Boolean(Math.floor(Math.random() + 0.5));
}
sendMessage(message) {
console.log(`Sending message: ${ message }`);
}
}
// implementation of an async `around` modifier.
function asyncAround(proceed, handler, target) {
return async function (...args) {
return (
await handler.call(target ?? null, proceed, handler, args)
);
};
}
</script>