docs(lib): add docs for `lib.channel`.

This commit is contained in:
Ansolve 2023-11-20 00:05:01 +08:00
parent 28cc47d535
commit 1362ab457d
No known key found for this signature in database
GPG Key ID: 2F2873AC9538CC2D
1 changed files with 31 additions and 6 deletions

View File

@ -357,11 +357,32 @@
/** /**
* **无名杀频道推送机制** * **无名杀频道推送机制**
* *
* 模拟`Golang``channel`仅保留部分特征 * 鉴于`Javascript`的特性及自身对所需功能的思考这是一个参考`Golang``channel`设计的完全和`go channel`不一样的异步消息传递对象
*
* 当且仅当接收方和发送方均存在时进行消息传递完全保证信息传递的单一性发送方/接收方一旦确定则无法更改和准确性发送方必然将消息发送给接收方
*
* 若存在发送方/接收方时调用`send`/`receive`将报错
*
* 若需要异步/不报错发送信息请等待`lib.actor`
* *
* @template T * @template T
* @example
* // 创建一个频道
* const channel = new lib.channel();
*
* // 从某个角落接收channel发出的消息若无消息则等待
* const message = await channel.receive();
*
* // 从某个角落向channel发消息若无消息接收则等待
* await channel.send(item);
*/ */
channel: class { channel: class {
/**
* @template TValue
* @callback PromiseResolve
* @param {TValue} value
* @returns {void}
*/
constructor() { constructor() {
/** /**
* @type {"active" | "receiving" | "sending"} * @type {"active" | "receiving" | "sending"}
@ -369,13 +390,15 @@
this.status = "active"; this.status = "active";
/** /**
* @type {Promise<T> | [T, Promise<void>] | null} * @type {PromiseResolve<T> | [T, PromiseResolve<void>] | null}
*/ */
this._buffer = null; this._buffer = null;
} }
/** /**
* @param {T} value * 向该频道发送消息在消息未被接受前将等待
*
* @param {T} value - 要发送的消息
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
send(value) { send(value) {
@ -387,7 +410,7 @@
break; break;
case "receiving": case "receiving":
/** /**
* @type {Promise<T>} * @type {PromiseResolve<T>}
*/ */
const buffer = this._buffer; const buffer = this._buffer;
this._buffer = null; this._buffer = null;
@ -404,7 +427,9 @@
} }
/** /**
* @returns {Promise<T>} * 接收频道所发送的消息若无消息发送则等待
*
* @returns {Promise<T>} 接收到的消息
*/ */
receive() { receive() {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
@ -415,7 +440,7 @@
break; break;
case "sending": case "sending":
/** /**
* @type {[T, Promise<void>]} * @type {[T, PromiseResolve<void>]}
*/ */
const buffer = this._buffer; const buffer = this._buffer;
this._buffer = null; this._buffer = null;