feat(lib): just add `lib.channel` which emulating channel of golang.

This commit is contained in:
Rintim 2023-11-19 23:25:23 +08:00
parent 2b2e8885dc
commit 28cc47d535
No known key found for this signature in database
GPG Key ID: BE9E1EA615BACFCF
1 changed files with 77 additions and 0 deletions

View File

@ -354,6 +354,83 @@
}
}],
},
/**
* **无名杀频道推送机制**
*
* 模拟`Golang``channel`仅保留部分特征
*
* @template T
*/
channel: class {
constructor() {
/**
* @type {"active" | "receiving" | "sending"}
*/
this.status = "active";
/**
* @type {Promise<T> | [T, Promise<void>] | null}
*/
this._buffer = null;
}
/**
* @param {T} value
* @returns {Promise<void>}
*/
send(value) {
return new Promise((resolve, reject) => {
switch (this.status) {
case "sending":
// TODO: handle the error.
reject(new Error());
break;
case "receiving":
/**
* @type {Promise<T>}
*/
const buffer = this._buffer;
this._buffer = null;
buffer(value);
this.status = "active";
resolve();
break ;
case "active":
this.status = "sending";
this._buffer = [value, resolve];
break;
}
});
}
/**
* @returns {Promise<T>}
*/
receive() {
return new Promise((resolve, reject) => {
switch (this.status) {
case "receiving":
// TODO: handle the error.
reject(new Error());
break;
case "sending":
/**
* @type {[T, Promise<void>]}
*/
const buffer = this._buffer;
this._buffer = null;
resolve(buffer[0]);
this.status = "active";
buffer[1]();
break ;
case "active":
this.status = "receiving";
this._buffer = resolve;
break;
}
});
}
},
/**
* **无名杀消息推送库**
*