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('事件名称', '发送的参数');
复制代码
eventPromise.emit(status: boolean, value: any = null);java
status = true 的状况下,任什么时候候都会直接响应 Promise
eventPromise.emitSuccess(value?: any);git
eventPromise.emitError(value?: any);github
eventPromise.awaitPromise();数据库
GitHub 传送门npm