event-promise 让事件回调,更容易使用Promise

EventPromise

安装

npm install e-promise
# or
yarn add e-promise
复制代码

它能够作什么?

在 Node 中,咱们常常须要链接数据库、Redis、Mq、Socket、Rpc等等,它们都是基于回调通知是否链接成功,在链接成功的时候才能进行对应的操做,EventPromise 就是专门为了解决它而存在,让你使用同步的形式调用异步的回调。javascript

例子

// 这里用 socket.io 举个例子,其它的触类旁通
const EventPromise = require('e-promise');
class IoEventPromise extends EventPromise {
	constructor() {
		super({
			// 设置超时时间,若是超过为异常
			timeout: 1000,
			// 设置 awaitPromise 最大的调用次数,若是超过为异常
			maxCall: 100
		});
		const server = require('http').createServer();
		const io = require('socket.io')(server);
		io.on('connection', client => {
			client.on('disconnect', () => {
				// 链接失败
				this.emitError('disconnect');
			});
			// 链接成功
			this.emitSuccess(client);
		});
		server.listen(3000);
	}
	async emit (eventName, ...args) {
		const client = await this.awaitPromise();
		// 链接失败,则直接输出错误
		if (!client || typeof client === 'string') {
			console.log(client);
			return;
		}
		// 链接成功,直接发送事件
		client.emit(eventName, ...args);
	}
}

const io = new IoEventPromise();
// 这里你就能够当即调用,发送事件,等 socket 链接成功后自行发送
io.emit('事件名称', '发送的参数');

复制代码

options

  • options.timeout
    • 在异常的状态下,Promise超时时间,将会直接结束Promise,返回响应结果
    • default: 1000ms
  • options.maxCall
    • eventPromise.awaitPromise(); 在异常的状态下,超过最大的调用次数,将会直接结束Promise,返回响应结果
    • defalut: 100

API

  • eventPromise.emit(status: boolean, value: any = null);java

    • status = true 的状况下,任什么时候候都会直接响应 Promise
    • status = false 的状况下,将会等待 options.timeout 或 options.maxCall 触发的时候结束 Promise
    • value Promise 的返回值
  • eventPromise.emitSuccess(value?: any);git

    • 会当即响应 Promise 结果
  • eventPromise.emitError(value?: any);github

    • 若是在 options.timeout 和 options.maxCall 指定的限制内,没有执行 eventPromise.emitSuccess() ,将会响应本结果
  • eventPromise.awaitPromise();数据库

    • 等待 Promise 响应,而且能够拿到返回值

GitHub 传送门npm

相关文章
相关标签/搜索