UNPKG

kitten-cloud-function

Version:

用于编程猫源码云功能(云变量、云列表等)的客户端工具

64 lines (63 loc) 1.75 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.Signal = void 0; /** * 信号,用于向外界发送消息。 */ class Signal { constructor() { this.slots = []; } /** * 连接一个消息接收函数,当有消息被发送时,该函数将被调用。 * * @param slot 接收函数 */ connect(slot) { this.slots.push(slot); } /** * 断开一个消息接收函数,使其不再接收消息。如果该函数不在接收列表中,则什么也不做。 * * @param slot 要断开的接收函数 */ disconnect(slot) { const index = this.slots.indexOf(slot); if (index >= 0) { this.slots.splice(index, 1); } } clear() { this.slots = []; } isEmpty() { return this.slots.length == 0; } emit(message) { this.slots.slice().forEach((slot) => { slot(message); }); } /** * 等待消息被发送或超时。 * * @param timeout 超时时间(毫秒),`0` 表示永不超时。 * @returns 一个 Promise 对象,当收到消息时,该对象将被 resolve,如果等待超时,则该对象将被 reject。 */ wait(timeout = 0) { return new Promise((resolve, reject) => { const slot = (message) => { this.disconnect(slot); resolve(message); }; this.connect(slot); if (timeout > 0) { setTimeout(() => { this.disconnect(slot); reject(new Error("Timeout")); }, timeout); } }); } } exports.Signal = Signal;